У меня есть приложение Node JS, которое действует как сервер и обрабатывает данные посредством POST запроса и работает на другом порту. С другой стороны, у меня есть другое веб-приложение jQuery, которое действует как клиент и отправляет почтовый запрос в приложение Node JS.
Когда я пытаюсь отправить данные от клиента jQuery, выдается ошибка, как показано ниже
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
Ниже мой Node JS и я добавил любой домен для доступа к Node JS приложению
// 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();
});
Мой клиент jquery выглядит так, как показано ниже, который отправляет данные в 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":"*"
}
});