Reputation: 445
I'm exploring backbone js, my requirement is to post the user details like name, email id, etc to the webservices. But when I run the application, I'm getting error like,
On Chrome,
XMLHttpRequest cannot load localhost:8080/service/customer/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8050' is therefore not allowed access.
On Firefox,
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:8080/service/customer/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Headers responses from both the browsers are,
I have researched on internet and identified as CORS issue, but I'm confused like is there any code configuration that I need to add in my JS files and where to put those codes. If there is any code, do I need to put the code in separate js file?
Here are my code snippets from my validation js files,
var ValidationModel = Backbone.Model.extend({
urlRoot: 'http://localhost:8080/service/customer',
defaults: {
ID: '',
fname: '',
lname: '',
email: ''.....
myValidationModel.save(myValidationModel.attributes,
{
success: function(model, response, options){
console.log('Model Saved..');
console.log('ID: ' + myValidationModel.get('id'));
},
error: function(model, xhr, options){
console.log('Failed to save model');
}...
I'm sincerely requesting you friends as I am new to this, could you please give me an idea, guidance, suggestions on how to resolve this issue, and also where to put the code. It would be a great favour if you could link me to any useful articles.
Thank you so much.
Upvotes: 1
Views: 778
Reputation: 3565
This is a server side issue. This provides a nice summary of how to enable CORS on different platforms.
If you are confused because you are developing locally then be aware that different PORT numbers can also throw CORS errors.
For example I have a server at http://localhost:8080 with a website running on it. I also have another website at http://localhost:8082 which consumes services from the one on 8080, this results in CORS issues.
The only thing to be aware of on client side is that if you adding any additional headers then CORS on server side must be configured to allows these headers. For example I add the following security token so that backbone can access the model data on server side:
$.ajaxSetup({
headers : {
"X-Auth-Token" : usercredentials.getAccessToken(),
}
});
This means that CORS on server-side must allow for the header X-Auth-Token
. If you are not adding any additional headers then usually you only need to configure the Origin
and allow the relevant methods GET
, POST
, PUT
, etc . . .
In your case it looks like you must configure CORS on your server to allow POST
calls from the Origin
localhost:8080
. The client will automatically add this header. The server just needs to allow it.
Upvotes: 1