Axios是否支持Set-Cookie?是否可以通过Axios HTTP请求进行身份验证?

时间:2018-09-28 05:49:26

标签: express cookies axios

我正在尝试使用Axios HTTP请求调用对Express API后端进行身份验证。 我可以在响应标题中看到“ Set-Cookie”,但未设置cookie。是否可以通过Axios HTTP调用设置cookie?

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 355
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Sep 2018 05:59:01 GMT
ETag: W/"163-PAMc87SVHWkdimTJca7oRw"
Set-Cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; Max-Age=3.6; Path=/; Expires=Fri, 28 Sep 2018 05:59:04 GMT; HttpOnly
X-Powered-By: Express

4 个答案:

答案 0 :(得分:6)

尝试一下!

axios.get('your_url', {withCredentials: true}); //for GET
axios.post('your_url', data, {withCredentials: true}); //for POST
axios.put('your_url', data, {withCredentials: true}); //for PUT
axios.delete('your_url', data, {withCredentials: true}); //for Delete

有关axios文档的详细信息,请参见

“ withCredentials指示是否应使用凭据发出跨站点访问控制请求”-https://github.com/axios/axios

有关凭证的更多详细信息:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

答案 1 :(得分:1)

万一其他人遇到我遇到的问题,

这是我对类似问题https://stackoverflow.com/a/62821342/8479303

的回答的转贴

在我的情况下,网络面板显示响应具有“ Set-Cookie”标头,但是在axios中,标头不会显示,并且正在设置cookie。

对我来说,解决方法是设置Access-Control-Expose-Headers标头。

为进行解释,从this comment到axios存储库中的一个问题,我被定向到这个person's notes,这导致我设置了Access-Control-Expose-Headers header -现在cookie已正确设置在客户。

因此,在Express.js中,我不得不在我的cors中间件中添加exposedHeaders选项:

const corsOptions = {
  //To allow requests from client
  origin: [
    "http://localhost:3001",
    "http://127.0.0.1",
    "http://104.142.122.231",
  ],
  credentials: true,
  exposedHeaders: ["set-cookie"],
};

...

app.use("/", cors(corsOptions), router);

同样重要的是,在axios端,我使用withCredentials配置来跟踪我想包含cookie的axios请求。

ex /

const { data } = await api.get("/workouts", { withCredentials: true });

答案 2 :(得分:0)

是的,您可以通过 Axios 设置Cookie。 Cookie需要传递到标头对象中。您可以在get / post / put / delete / etc中发送cookie。请求: 正如 Aaron所建议的:

axios.get('URL', {
  withCredentials: true
}); 
axios.post('URL', data, {
withCredentials: true
}); 
axios.put('URL', data, {
withCredentials: true
});
axios.delete('URL', data, {
withCredentials: true
});

或者您也可以尝试以下方法:

axios.get(url, {
            headers: {
                Cookie: "cookie1=value; cookie2=value; cookie3=value;"
            }
        }).then(response => {
              console.log(response);
});

答案 3 :(得分:0)

我尝试设置/usr/bin/ld: cannot find -lbz2 collect2: error: ld returned 1 exit status ,但仍然出现此错误:

跨域请求被阻止:相同来源策略不允许读取位于http:// localhost:4000 / users / register的远程资源。 (原因:CORS请求未成功。)

CORS被配置为允许来自前端端口的请求。

我不得不像这样更改axios的默认选项:

withCredentials: true

问题解决了。没有错误,Set-Cookie可以正常工作。

相关问题