This issue may not be a new problem for many newbie. I am one among them and I have to handle this issue on client side. So, please don't mark this issue as duplicate.
I have my website client code deployed in a server and this website calls a webservice deployed in some other different server. (Please note: I don't have this webservice code access).
My AJAX code to retrieve data:
$.ajax({
type: 'GET',
url: 'http://webservice_url',
success: function (data) {
//success
},
failure: function(error){
//error
}
});
On accessing this webservice through AJAX, I receive:
XMLHttpRequest cannot load http://webservice_url. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Browser console log:
- I can view my webservice's response successfully in browser console (under 'Network' tab -> 'response' tab of my webservice). However, retrieving the above error.
On reviewing many previous posts, I found that by setting response header as:
response.addHeader("Access-Control-Allow-Origin", "*");
will fix this issue.
However, I don't have access to change my webservice code, to add response header. I have to fix this in website.
I have developed this website using ExpressJS and Node. My app code is
var http = require('http');
var routes = require('./routes');
var express = require('express');
var path = require('path');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.cookieParser('secret code'));
app.use(express.logger('dev'));
app.use(express.favicon());
app.use(express.methodOverride());
app.use(express.session());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Pass to next layer of middleware
next();
});
app.get('/', routes.index);
http.createServer(app).listen(3000, function(){
console.log('Express server started successfully');
});
Adding res.setHeader('Access-Control-Allow-Origin', '*')
haven't helped me.
Can anyone guide me.