无需cookie即可发送React POST请求

时间:2020-06-25 23:02:55

标签: reactjs express cookies axios

我在Axios POST请求中苦苦挣扎,但确实希望在其标头中发送cookie。

我的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))

再次感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我认为这与以下问题有关: https://github.com/axios/axios/issues/876

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

EXPECT_CALL(mock_pthread, pthread_create(_,_,_,_))
    .WillOnce(DoAll(
                SaveArg<2>(&cllbk),
                Return(1)
                ))
相关问题