I am new to node.js and got stuck on cors problem. I am sending client ajax get request from one express server to another, but at least I am not able to get response from app.all('*', function(req, res, next){console.log("request: "+req)})
GET request looks something like:
$.ajax({
type: 'GET',
url: 'http://localhost:8082/request'
});
I was also setting headers in ajax with:
'beforeSend : function(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Max-Age', '1000');
xhr.setRequestHeader('Authorization', '*')},
...or setting cors module in node.js:
var cors = require('cors');
var app = express();
app.use(cors());
app.options('*',cors(),function(){
console.log("preflight")
});
In both firefox and chrome, I received no response (in chrome I got net::ERR_CONNECTION_REFUSED
)
When running node servers locally on my PC, everything works. Also curl command works fine.
Is there a chance, this is a problem with hosting/ports or am I still missing something?
expressjs is serverside code so it can't use jquery ajax like that.
Node, Ajax and JavaScript integration html file and refresh the web browser. Uploads to Node. js will go through Ajax, and thus create a full JavaScript file uploader with JavaScript running both on the client and the server. And that's how easy it is to create a Node.
NodeJs is an open-source framework based on JavaScript v8 engine. AJAX is a web development technique for making asynchronous calls to the server. jQuery is a JavaScript library for designing and make some web development tasks easy. It makes it possible to run javascript outside of the browser.
You don't need to set the CORS headers on your $ajax call, as those headers are required by the browser in the HTTP Response header.
For cross domain AJAX, make sure you set the crossDomain
flag on the $ajax option:
$.ajax({
url: url,
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
A clean way to handle CORS requests in your express endpoints would be to create a middleware that you add to express routes that respond to cross origin requests:
cors.js
module.exports = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
Then make sure you add the middleware to the express endpoint:
app.post(url, cors, function(req, res) {
});
I had same issue and solved with this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With