【问题标题】:React POST request is sent without cookieReact POST 请求是在没有 cookie 的情况下发送的
【发布时间】:2020-06-26 20:56:42
【问题描述】:

我正在处理一个确实想在其标头中发送 cookie 的 Axios POST 请求。

我的 API 路由 /search/producers 正在与 Postman 合作:登录后,此路由会以正确的数据回答。

使用axios POST请求,服务器找不到req.user,因为没有发送cookie。

在我的浏览器中,我总是收到401 OPTIONS 响应。

响应头:

OPTIONS /search/producers HTTP/1.1
Host: localhost:4242
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: */*
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,withcredentials
Referer: http://localhost:3000/home
Origin: http://localhost:3000
Connection: keep-alive

请求标头:

HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Content-Type: application/json; charset=utf-8
Content-Length: 28
ETag: W/"1c-IxTdph/1tV0PHzy4xuP38jYWJTg"
Date: Thu, 25 Jun 2020 22:26:37 GMT
Connection: keep-alive

这是我的服务器端代码:

检查req.user的函数(用Passport创建)

function isAuthenticated (req, res, next) {
    console.log(req.headers.cookie) // always undefined with Axios request
    if (req.user){
        return next();
    }else{
        return res.status(401).json('Denied access')
    }
}
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD, OPTIONS");
    next();
});
app.use('/search', isAuthenticated, searchRoutes); // OK with Postman POST, blocks with Axios POST

路线本身:

router.post('/producers', function(req, res) {
    if (req.body.product) {
        Producers.find({productsCategories: {$regex: req.body.product, $options: 'i'}})
          .then(result => {
              return res.json(result)
          })
          .catch(error => {
              return res.json("Internal Server Error")
          })
    }
})

我设置了withCredentials: true客户端:

const instance = axios.create({
  withCredentials: true,
})
instance
  .post("search/producers", { product })
    .then(res => {
      ...
    })

所有“GET”请求都能完美运行,在请求标头中发送 Cookie。

你能帮我弄清楚我的代码有什么问题或遗漏吗?感谢您的任何想法。

[EDIT] 我决定使用 npm 包 cors 并且它起作用了:

对于那些感兴趣的人:

const cors = require('cors');
const corsOptions = {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    credentials: true
}

app.use(cors(corsOptions))

再次感谢您的帮助。

【问题讨论】:

  • 如果您在每次调用中发送 withCredentials 属性而不是使用实例会发生什么?

标签: reactjs express cookies axios


【解决方案1】:

我相信它与这个问题有关: https://github.com/axios/axios/issues/876

将您的 API 调用替换为以下内容

axios({
  url: API_BASE + "search/producers",
  withCredentials: true
  method: "POST",
  data: qs.stringify(product), 
}).then(response => {
...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-15
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2023-03-19
    • 1970-01-01
    • 2010-10-02
    相关资源
    最近更新 更多