jquery - 被 CORS 策略阻止 : Request header field access-control-allow-origin is not allowed

标签 jquery node.js

我有一个 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())

https://www.npmjs.com/package/cors

关于jquery - 被 CORS 策略阻止 : Request header field access-control-allow-origin is not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237510/

相关文章:

javascript - 窗口底部的 div,而不是页面

javascript - 需要时 Node 模块未定义

javascript - Syncano 对多个字段进行条件过滤

jquery - 找不到最近的 table

jquery - 调整窗口大小时获取模态动态调整大小

mysql - 为现有 MySQL 数据库定义 Sequelize 模型

node.js - “抽象类型X必须在运行时解析为具有值的字段Query.user的对象类型

node.js - 将 Node.js 应用程序部署到 Heroku 时出现应用程序错误

jquery - 我可以将 tagit 与 twitter bootstrap 一起使用吗?

jquery - 如何使用lightbox插件colorbox?