Reactjs 连接到API时出现反应、节点、表示错误
我发现错误:Reactjs 连接到API时出现反应、节点、表示错误,reactjs,api,express,endpoint,Reactjs,Api,Express,Endpoint,我发现错误: 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 there
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.
这是我的异步帖子:
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(未找到) 及 SyntaxError:JSON中位置0处出现意外标记<
我现在能做什么?您不能从express服务器返回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' });
});
您没有从express服务器返回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' });
});
这与我的答案相同吗?这与我的答案相同吗?仍然。StepOneValidationForm.js:42 SyntaxError:Unexpected token<在JSON中的位置0确定现在我如何显示此数据?问一个新问题。仍然。StepOneValidationForm.js:42 SyntaxError:Unexpected token<在JSON中的位置0确定现在如何显示此数据?提出一个新问题。