【问题标题】:React proxy uses the wrong urlReact 代理使用了错误的 url
【发布时间】:2019-12-11 08:02:27
【问题描述】:

我已通过代理对我的节点 js 服务器 http://localhost:3000http://localhost:9000 做出反应 在我的 package.json 反应应用中:

...
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:9000",
...

一些请求错误的作品。 例子: 我在我的反应应用程序上http://localhost:3000/admin 并创建对服务器的请求

fetch('admin/check-token',
                {
                    method: "GET",
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization':Cookie.getCookie(TOKEN)
                    },
                })
                .then(response => {
                    return response.json();
                })
                .then((json) => {
                    console.log(json)
                })
                .catch(function (res) {
                    console.log(res)
                })

我需要向http://localhost:9000/admin/check-token 提出请求,但我有错误,Chrome 显示我向http://localhost:9000/admin/admin/check-token 发送请求。 据我了解,额外的/admin 取自http://localhost:3000/admin。 我做错了什么?

【问题讨论】:

    标签: node.js reactjs proxy request


    【解决方案1】:

    您的浏览器 URL(window.location.href) 是 http://localhost:3000/admin,为获取提供的 URL 字符串是 admin/check-token。根据设计,它们正在被附加。要仅使用浏览器 URL 中的域部分,请以 / 开头您的获取 URL 字符串,例如,

    fetch('/admin/check-token', ...)
    

    或者您可以提供完全限定的 URL,例如,

    fetch('http://localhost:3000/admin/check-token', ...)
    

    【讨论】:

      【解决方案2】:

      如果您有快速路线,则只需使用两个 /admin,例如在您的主文件中

      app.use('/admin', adminRoutes)
      

      然后在您的管理路线中

       adminRoutes.post('/admin', (req, res) => {
        // do stuff
        })
      

      那么你的 fetch 看起来像

      fetch('http://localhost/admin/admin', {
        method: "POST" //etc...
        })
      

      但是如果你使用 jsonwebtoken 你应该在后端使用中间件

      adminRoutes.post('/adminTasks', authenticateToken, (req, res) => {
        // if authenticateToken do stuff
      })
      

      为了更好的例子,我将展示 authenticateToken 函数

      function authenticateToken(req, res, next){
          const authHeader = req.headers['authorization'];
          const token = authHeader && authHeader.split(' ')[1];
          if(token == null) { return res.sendStatus(401) }
      
          jwt.verify(token, process.env.ACCESS_TOKEN, (err, user) => {
              if(err) { return res.sendStatus(403) }
              req.user = user;
              next();
          })
      

      }

      【讨论】:

        猜你喜欢
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 2018-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        相关资源
        最近更新 更多