我有一个 Node JS 应用程序,它充当服务器,通过 POST 请求处理数据并在其他端口上运行。在另一部分,我有另一个 jQuery Web 应用程序,它充当客户端,并将 post 请求发送到 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":"*"
}
});
最佳答案
您可以使用 CORS 库。常见的地方可以看到上面设置的中间件
app.use(function (req, res, next) {
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
关于jquery - 被 CORS 策略阻止 : Request header field access-control-allow-origin is not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237510/