【问题标题】:How should i setup headers at server and client?我应该如何在服务器和客户端设置标头?
【发布时间】: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


【解决方案1】:

我在这里找到答案 https://www.youtube.com/watch?v=zoSJ3bNGPp0

或在服务器上使用此中间件 (YEAA BOY)))))))))))))))))))) (浪费了 6 小时:(())

router.use(    function (req, res, next){
 res.header("Access-Control-Allow-Origin", "http://localhost:3000");
 res.header("Access-Control-Allow-Headers", "Origin, X-Request-With, Content-Type, 
Accept, Authorization");
 res.header("Access-Control-Allow-Credentials", 'true');

/*    res.header("Access-Control-Allow-Headers", 'Origin, X-Request-With, Content-Type, 
 Accept, Authorization');
res.header("Access-Control-Expose-Headers", 'Authorization, Uid');*/ 

  if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
return res.status(200).json({});
  }
  next();
});

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 2012-05-26
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多