posting json to express - invalid json - json

I am trying to post some json to a node server running express but it keeps telling me the json was invalid. But its not, its just a plain old object. Currently I get the error 'unexpected token i'
client:
$.ajax({
contentType: 'application/json',
type: "POST",
url: "/admin",
data: {id: '435ghgf545ft5345', allowed: true}
});
server:
var bodyParser = require('body-parser');
app.use(bodyParser({strict: false}));
app.post('/admin', function(request, response) {
console.log(request.body);
});
I have also tried putting bodyParser.json() as the second parameter in the post route and get the error 'invalid json at parse'. I cant figure out why.

This code may help you :
var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true});
$.ajax({
type: 'POST', //GET or POST or PUT or DELETE verb
async: false,
url: '/admin', // Location of the service
data: jsondataResource , //Data sent to server
contentType: 'application/json', // content type sent to server
dataType: 'json', //Expected data format from server
processdata: true, //True or False
crossDomain: true,
success: function (msg, textStatus, xmlHttp) {
result = msg;
},
error: ServiceFailed // When Service call fails
});
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}

Related

flask-cors is not parsing the data from ajax client

I am using flask for creating some endpoints for a blockchain project . I need to accept json data from ajax client . Since it is cros platform , i am using flask cors . But i cant seem to find a solution. It is not working
I have already tried doing
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origin = '*')
Basically my client code is as follows .
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: true
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
And at my server i have an endpoint of
#app.route('/ratings/new', methods = ['POST','OPTIONS'])
def rating():
values = request.get_json()
if values == None:
return "No data received", 400
#ratings = values['rating']
index = blockchain.new_ratings(values)
response = {
'Message': f'New transaction will be added to the block {index}',
}
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin','*')
return response, 201
At the server side i am not receiving the required data and at the client side i am getting the following error .
Access to XMLHttpRequest at 'http://localhost:8080/ratings/new' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please help me solve this problem . Thanks in advance.
Silly mistake , make the withCredentials: false
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: false
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});

Json Error In Laravel Ajax

I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Laravel Code:
return response()->json('ok');
Jquery Code:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText); console.log(errors);
$.each(errors, function(index, value) { $.gritter.add({
title: 'Error',
text: value
});
});
}
RedyState=4
Staus = 200
Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
echo "hi";
return response()->json('ok');
});
It would cause parse error.
With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);
You javascript code should be
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success:function (xhr){
var data = xhr.data;
},
error: function (error){
}
});
And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?

Get value from an odata property in a JSON response using ajax

I need to get the value for #odata.context property from the following Json response in ajax:
{
"#odata.context":"https://site.sharepoint.com/_api/",
"#odata.type":"#oneDrive.permission",
"#odata.id":"https",
"link":{"scope":"anonymous"}
}
I would like to do something like that in code:
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.#odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1
}
});
I think you can get data by this:
data["#odata.context"]
And about the JSON.parse throw exception, it caused by the data is not a JSON string.
Example

Ajax Call using jsonp for calling rest webservice from other domain

How I use the jsonp when call to rest webservice from different domain.becouse my simple json does not working for rest webservice.how can i call rest webservice for ajax call.i use both jsonp and javascript for that.server responce i seen on only browser in firebug but how to show it on my application
my JS code.
function callService() {
$.ajax({
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
crossDomain: true,
cache: false,
async: false,
contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
alert("Server Responce Successfully!..");
},
error: function (msg) {
alert('error ' + msg.d);
}
});
}
function countryProvinceWCFJSONMulti() {
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = 'JSON';
script.src = "http://192.168.15.213/myservice/Service.svc/GetEvents";
script.type = "text/javascript";
head.appendChild(script);
varType = "GET";
varData = '{"username": "' + "Suhasusername" + '","password": "' + "suhaspassword" + '"}';
varContentType = "application/JSONP; charset=utf-8";
varDataType = "JSONP";
varProcessData = true;
callService();
}
If the same-origin policy isn't an issue, your code should look something like this:
$.ajax({ url: url,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
alert("Server Response Successful!..");
}
});
Here is a question that talks about circumventing the same-origin policy

JSON data not parsing in node.js displays undefined in console

JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.