【发布时间】:2020-11-20 09:07:48
【问题描述】:
我已经用 nodejs 编写了服务器并在路径上添加了处理程序
// /api/friend/
router.get("/search/:userSearchParam" , async (req, res) => {
let user = await User.find(
{ name: { $regex: req.params["userSearchParam"], $options: "i" } },
{ name: 1, _id: 1 }
);
if (user.length > 0) {
res.json(user);
} else {
res.sendStatus(204); //json({"message": 'З даним іменем нікого немає'})
}
});
当我在互联网上发现允许 CORS 时,我添加了中间件
withAuth: function (req, res, next){
res.header("Access-Control-Allow-Credentials", 'true');
res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
res.header("Access-Control-Allow-Headers", 'Authorization, X-Custom-Header');
/* res.header("Access-Control-Allow-Headers", 'Origin, X-Request-With, Content-Type, Accept, Authorization');
res.header("Access-Control-Expose-Headers", 'Authorization, Uid'); */
next();
}
服务器正在本地主机上运行
但是当我尝试从 React (localhost:3000) 加载数据时
handleChange(event) {
const val = event.target.value;
const auth = this.state.auth;
console.log(this.state.auth);
this.setState({
[event.target.name]: val,
});
if (val.length > 3) {
axios.get("http://localhost/api/friend/search/" + val, {
headers: {
'Authorization': this.state.auth,
'Origin': 'http://localhost:3000',
},
credentials: "include",
})
.then(function (response) {
if (response.status === 200) {
console.log(response);
}
})
.catch((err) => {
console.log(err);
// alert(err.response.data.message);
});
}
}
render() {
我应该如何在服务器和客户端设置标头?
【问题讨论】:
-
客户端也不向服务器发送授权
-
"http://localhost/api/friend/search/" + val在你的代码中应该是":3000/api/friend/search/" + val,缺少端口并且不要硬编码域 -
我在 80 端口上运行节点服务器,而我的 react 应用程序在 3000 端口上,这就是为什么我试图找到解决 CORS 的方法,或者我不明白什么?
标签: node.js reactjs http-headers basic-authentication