发出发布请求时出现NodeJS CORS错误
Posted
技术标签:
【中文标题】发出发布请求时出现NodeJS CORS错误【英文标题】:NodeJS CORS error when making a post request 【发布时间】: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
否则部署后有问题)
【参考方案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
【讨论】:
以上是关于发出发布请求时出现NodeJS CORS错误的主要内容,如果未能解决你的问题,请参考以下文章
发出 GET 请求时没有 CORS 错误,但发出 POST 请求时出现 CORS 错误
发出 POST 请求时出现 Google Cloud Function CORS 错误