【问题标题】:NodeJS CORS error when making a post request发出发布请求时出现NodeJS CORS错误
【发布时间】:2021-03-02 01:30:45
【问题描述】:

我有一个 node js 应用程序,我将表单数据从客户端转发到服务器,以将这些数据存储在 mongoDB 中。

要将数据发送到服务器,我使用带有 API_URL 的 POST 请求:http://localhost/mews

每当执行 POST 请求时,我都会在客户端的控制台中看到 CORS 错误。

客户端 JS

const API_URL = "http://localhost/mews";

form.addEventListener('submit', async (event) => {
    event.preventDefault();

    const formData = new FormData(form);
    //Grab the form values
    const name = formData.get('name');
    const content = formData.get('content');

    const mew = {
        name,
        content
    }

    //send the mew information to the server
    const response = await fetch(API_URL, {
        method: "POST",
        body: JSON.stringify(mew),
        headers: {
            'Content-Type': 'application/json'
        }
    });
    const json = await response.json();
    console.log(json);

});

服务器端 JS

const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');

var corsOptions = {
    origin: 'http://localhost/mews',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
} 


const app = express();
app.use(cors(corsOptions));
app.use(express.json());

function isValidMew(mew) {
    return mew.name && mew.name.toString().trim() !== '' &&
        mew.content && mew.content.toString().trim() !== '';
}

//chen user sends a message (POST)
app.post('/mews', async (req, res) => {

    if (isValidMew(req.body)) {

        const mew = {
            name: req.body.name.toString(),
            content: req.body.content.toString(),
            created: new Date()
        };

        console.log(mew);

        const createdMew = await mewe.insert(mew);
        res.json(createdMew);

    } else {
        res.status(422);
        res.json({
            message: 'Hey! Name and Content are required!'
        });
    }
});

app.listen(4000, () => {
    console.log("Listening on http://localhost:4000/");
});

发出发布请求时客户端控制台出现错误

Cross-Origin Request Blocked: The Same Origin Policy does not allow reading of the remote resource at http: // localhost / mews. (Reason: CORS request was unsuccessful).

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

【问题讨论】:

  • 服务器在 4000 端口而不是 80 端口上运行,更改 API_URL 以适应(删除 http://localhost 否则部署后有问题)

标签: javascript node.js post cors


【解决方案1】:

这适用于我使用 "cors": "2.8.5"

const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');

const app = express();
app.use(express.json());
app.use(cors());

希望对你也有帮助,参考在这里https://www.npmjs.com/package/cors

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 2017-08-15
    • 2022-01-06
    • 2022-01-23
    • 2021-06-18
    • 2016-09-15
    • 2019-05-03
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多