【发布时间】: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