The 'Uncaught SyntaxError: Unexpected token : ' in jsonp - node.js

I have already get the response json data from server to browser, but it is confused that the data can not be displayed in the browser and I found the error in the console that told me 'Uncaught SyntaxError: Unexpected token :'. Here is my code in node js.
function callFacebook(){
$.ajax({
url: "http://192.168.37.179:8888/facebook/connect?callback_=[TIMESTAMP]",
type: "GET",
dataType: "jsonp",
jsonp:"jsonp",
cache: true,
timeout: 5000,
success: function(data) {
execute(data);
},
error:function() { console.log('Uh Oh!'); }
});
}
and here is the response json data:
res.header('Content-Type','application/json');
res.header('Charset','utf-8');
res.send({"something": "father"});

From the server you are sending just normal JSON data, but on client you are expecting JSONP.
The response from server is not JSONP and browser does throw exception as syntax is wrong.
If you need to send JSONP from server, then if you are using express add extra use:
app.configure(function() {
app.set('jsonp callback', true);
});
Then to send JSONP just slightly change res. You don't need to set any header anymore, as they will be automatically detected:
res.jsonp({ hello: 'world' });
On client side, jQuery will add callback it self, so use just this simplified way:
$.ajax({
url: "http://192.168.37.179:8888/facebook/connect",
type: 'GET',
dataType: 'jsonp',
cache: true,
timeout: 5000,
success: function(data) {
console.log(data)
},
error: function(xhr, status, error) {
console.log('error[' + status + '] jsonp');
}
});
As well if your node is proxied through nginx or any other web platform, don't forget to enable utf8 encoding there.

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

How to handle http status codes in express from http post response and pass along to the angularjs controller

I am trying to handle various http status codes from my node/express and pass the response back to the angular. i get an error that Cannot set Headers after they are sent to the client. How do i Handle this based on response and also log for various http codes in nodejs?
app.post("/employees", function(req,res) {
var ServerOptions = {
method: 'POST',
uri: 'http://localhost:5001/api/empData',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json'
}
};
request(ServerOptions).then(function (Response) {
res.status(200).json(response);
})
.catch(function (err) {
res.status(401).json({message: "unauthorized"});
console.log("Unauthorized");
res.status(404 || 500).json({message: "error"});
console.log("Error");
res.set("Connection", "close");
});
});
According to angularjs documentation on $http, when server returns status other than 200, "error" callback is invoked.
Try placing your code for handling 401 status inside .error().

Cookies not being saved from jquery ajax

I have a rest server running locally and a front end server running locally aswell. The rest server uses restify and session-cookie with passportjs. This all seems to be working fine as im using Postman app to test the API where cookies are being found and saved:
Postman app image
But when i use ajax on my front end app to login, i do not receive the cookie. Or at least it does not seem to save. This is the ajax code:
$("form#login-form").submit(function(){
var data ={
email: $(this).find("input[name='email']").val(),
password: $(this).find("input[name='password']").val()
};
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: URL + "/login",
data: data,
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
if(data.error){
console.log("logged in error:" + data.error);
}
else {
console.log("logged in:" + data.LoggedIn);
window.location.replace("/");
}
}
});
But the front end acts like it does log me in with each page displaying the right user info and logging out works perfectly too, but i cannot find a stored session for the page anywhere in chrome or firefox dev tools.
What could be causing this?

JSONP cross domain request,but server return a json?

A Cross-domain request bothered me. I want to use ajax request jsonp data from a third-party data-bank. But some works, some not, maybe the callback jsonp-data is not supported, how can I fix it if the data-bank only return json?
function newcreateElement(url) {
$.ajax({
type: "get",
async: false,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function (json) {
$("#div pre code").html(JSON.stringify(json));
},
error: function (XMLHttpRequest, textStatus, readyState, status) {
alert(textStatus);
alert(XMLHttpRequest);
alert(readyState);
alert(status);
}
})
}

Node express gets 2 calls from single remote ajax call

I have a simple ajax call and when I debug on server side (node) I alays get 2 calls...
I thought it was becuase of favicon but I dont think it is because I
app.use(express.favicon('public/assets/favicon.ico'));
I even tried to just do a catch all for favicon so I am pretty sure its the not the issue:
app.post('/_html/favicon.ico', function (req, res) {
console.log('2222');
res.send('{"serverName": 1}');
});
here is the ajax code:
$.ajax({
url: some_url.html,
type: "POST",
crossDomain: true,
data: '{a: 1}',
dataType: "json",
contentType: "application/json",
success: function (res) {
alert(res.serverName);
console.log(res.serverName);
},
error: function (res) {
alert("Bad thing happend! " + res.statusText);
console.log("Bad thing happend! " + res.statusText);
}
});
and for some reason when I debug on node server side, I always get 2 calls from ajax
:(
why?
Thanks,
Sean.
It's preflighted request.
Cause you yse non-standard content type browser first send OPTIONS request and then real POST request with your data.
BTW, {a: 1} is invalid JSON. It must be {"a": 1}.

Resources