首页 > 解决方案 > React POST 请求是在没有 cookie 的情况下发送的

问题描述

我正在努力处理一个确实想在其标头中发送 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。

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

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

对于那些感兴趣的人:

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

app.use(cors(corsOptions))

再次感谢你的帮助。

标签: reactjsexpresscookiesaxios

解决方案


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

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

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

推荐阅读