CORS策略阻止了JSON的错误,但是切换标头类型修复了错误?
我制作了此简单的输入表单,该表单在将信息添加到它们时会显示数据。
因此,我遵循了本教程,他们使用 application/json
将此标头制作,用于通过输入字段渲染JSON数据。
let url = 'http://localhost:3000/';
let h = new Headers()
h.append('Content-type', 'application/json')
let req = new Request(url, {
headers: h,
body: json,
method: 'POST'
})
但是,阅读MDN文档,它表明只有3种内容类型,我不明白尝试显示JSON数据时要使用哪种内容。
根据文档,它说的是
It also needs to have a MIME type of its parsed value (ignoring parameters)
of either application/x-www-form-urlencoded, multipart/form-data, or text/plain.
,如果我只是将代码切换到此,错误就会消失,但是我不知道这是正确的方法。
h.append('Content-type', 'multipart/form-data')
let req = new Request(url, {
headers: h,
body: json,
method: 'POST'
})
在教程中,他说这仅显示错误,因为他使用了其他端口号而没有在服务器中解决该错误?
https://www.youtube.com/watch?v=gwjhe7licjs timeestamp 10: 40
但是,在此之前的一切都很好,直到他添加了JSON数据选项?
服务器代码
const http = require('http');
const server = http.createServer(function (req, res) {
req.on('data', function (data) {
//handle data as it is received... for POST requests
});
req.on('end', function () {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200, 'OK');
res.end('{ "data": "just a plain old json reply" }');
});
});
server.listen(3000, (err) => {
if (err) {
console.log('bad things');
return;
}
console.log('listening on port 3000');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cors需要 flight preflight请求跨原始请求并不简单。
如果要发送请求的端口与端口不匹配启动请求的HTML文档,则是交叉原始请求。
可以预置请求的一种方法是发送。
JSON不是您可以使用HTML表单发送的一种数据,因此,如果您发送JSON数据,则需要前飞行请求。
在这种情况下,您只是在撒谎您发送的数据类型。大概您还将设置服务器以忽略
content-type
请求标头,并尝试将请求主体解析为JSON。一种更好的方法是说明您发送的内容类型的真相,并配置服务器以授予前飞行的许可。
CORS requires a preflight request be granted permissions before a browser will make a cross-origin request that isn't Simple.
If the port the request is being sent to doesn't match the port the HTML document that initiated the request was served from, then it is a cross-origin request.
One way that a request can be make preflighted is to send a type of data you can't send with an HTML form.
JSON is not a type of data you can send with an HTML form, so if you send JSON data then a preflight request is needed.
In this case, you are just lying about what type of data you are sending. Presumably you are also setting up the server to ignore the
Content-Type
request header and try to parse the request body as JSON regardless.A better approach would be to tell the truth about what type of content you are sending, and configure the server to grant permission to the preflight.