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

问题描述 投票:5回答:2

我正在尝试使用Axios HTTP请求调用来验证快速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
express cookies axios
2个回答
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 docs的更多信息:

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

有关withCredentials的更多细节:

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


0
投票

是的,您可以通过Axios设置cookie。 Cookie需要传递到headers对象中。您可以在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);
});
© www.soinside.com 2019 - 2024. All rights reserved.