I have a Node JS app which acts as server and processes the data through POST request and running on other port.On the other part i have another jQuery web application which acts as client and sends the post request to Node JS app.
When i try to POST the data from jQuery client, it is throwing error as below
Access to XMLHttpRequest at 'http://localhost:3000/data' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
Below is my Node JS and i have added the any domain to access Node JS app
// Starting the App Server on Port 3000
app.listen(3000, function() {
console.log("Server running on port http://localhost:3000");
});
// set headers for allowing cross domain access
//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');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
My client jquery looks like below which post the data to Node JS
$(document).ready(function(){
$("button").click(function(){
console.log(" Entered inside click ");
$.ajax({
contentType: 'application/json',
data: '{"data":"<div>Some raw data pushed to node url</div>"}',
dataType: 'json',
success: function(data){
console.log(" Data Received ");
$("#content").append("Data received");
},
error: function(){
console.log(" Error while connecting for data");
},
processData: false,
type: 'POST',
url: 'http://localhost:3000/data',
headers: {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
});
You can employ CORS library. It is common place to see the middleware set above app.use(function (req, res, next) {
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
You need to remove the Access-Control-Allow-Origin header from the request. The header should only be included in the response. To me it seems like since it is not in the list of allowed headers and you don't specifically allow it in your Node app it causes the issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.