谁能帮我解决一些小问题吗? 我有 Express 应用程序,它完全可以处理 postman 的请求(添加、删除等) 现在,我想使用 fetch 方法将我的客户端(react.js)与现有 API 连接起来。
我有错误: 没有“no-cors”模式
App.js:121 POST http://localhost:3000/users/login net::ERR_ABORTED 400(错误请求)
使用“no-cors”模式
无法加载资源:服务器响应状态为 400(错误请求)
App.js 中的请求
handleLogInClick = (email, password) => {
email = "name@gmail.com";
password = "qweasd123";
console.log("Trying to login ");
fetch("http://localhost:3000/users/login", {
// mode: "no-cors",
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({ email: email, password: password }),
// body:({email:email, password:password})
})
.then((res) => res.json())
.then((data) => console.log(data));
};
这是 fetch 方法中传递的 body 的问题吗?或者服务器上的 CORS 问题?我不知道,也许更有经验的人知道这个问题的解决方案。
node.js 中的路由
router.post('/users/login', async (req, res) => {
try {
const user = await User.findByCredentials(req.body.email, req.body.password)
const token = await user.generateAuthToken()
res.send({ user, token })
} catch (e) {
res.status(400).send()
}
})
postman 的屏幕截图
感谢您的帮助,这是我在 StackOverflow 上的第一篇文章:)
最佳答案
补充一下,这里有一个快速 glance默认浏览器行为。
CORS or Cross Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs)
当 Web 应用程序请求与其自身具有不同来源(域、协议(protocol)或端口)的资源时,Web 应用程序会执行跨域 HTTP 请求。
跨源请求的示例:从 https://domain-a.com 提供的前端 JavaScript 代码使用 XMLHttpRequest 发出 https://domain-b.com/data.json 的请求.
出于安全原因,浏览器限制从脚本发起的跨源 HTTP 请求。例如,XMLHttpRequest 和 Fetch API 遵循同源策略。
正在安装this浏览器上的扩展程序将有助于解锁 CORS。
关于javascript - 从react.js 中的Express.js API 获取数据。 postman 的请求正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892798/