连接到 API 时出现 REACT、NODE、EXPRESS 错误
REACT, NODE, EXPRESS Error when connect to API
我收到错误:
localhost/:1 Failed to load http://localhost:5000/api/hello: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是我的异步 POST:
async function submitToServer(data){
try{
let response = await fetch('http://localhost:5000/api/hello', {
method: 'POST',
headers: {
'Content-type' : 'application/json',
},
body: JSON.stringify(data),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
这是我的服务器:
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.listen(port, () => console.log(`Listening on port ${port}`));
我应该怎么做才能将此信息发送到 API?
我是否需要创建端点或其他东西?
所以我安装了cors npm
。
现在我有这些错误:
POST localhost:5000/api/hello 404 (Not Found)
和
SyntaxError: Unexpected token < in JSON at position 0
我现在可以做什么?
您没有从您的快递服务器返回 JSON。
res.send({ express: 'Hello From Express' });
应该是
res.json({ express: 'Hello From Express' });
此外,您为 GET
定义了路由,但您发送了 POST
请求。所以你的处理程序应该是:
app.post('/api/hello', (req, res) => {
res.json({ express: 'Hello From Express' });
});
我收到错误:
localhost/:1 Failed to load http://localhost:5000/api/hello: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
这是我的异步 POST:
async function submitToServer(data){
try{
let response = await fetch('http://localhost:5000/api/hello', {
method: 'POST',
headers: {
'Content-type' : 'application/json',
},
body: JSON.stringify(data),
});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
这是我的服务器:
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.listen(port, () => console.log(`Listening on port ${port}`));
我应该怎么做才能将此信息发送到 API?
我是否需要创建端点或其他东西?
所以我安装了cors npm
。
现在我有这些错误:
POST localhost:5000/api/hello 404 (Not Found)
和
SyntaxError: Unexpected token < in JSON at position 0
我现在可以做什么?
您没有从您的快递服务器返回 JSON。
res.send({ express: 'Hello From Express' });
应该是
res.json({ express: 'Hello From Express' });
此外,您为 GET
定义了路由,但您发送了 POST
请求。所以你的处理程序应该是:
app.post('/api/hello', (req, res) => {
res.json({ express: 'Hello From Express' });
});