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

Man*_*akh 10 cookies express axios

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

访问控制允许来源:*
连接:保持活动状态
内容长度:355
内容类型:application / json; 字符集= utf-8
日期:2018年9月28日星期五05:59:01 GMT
ETag:W /“ 163-PAMc87SVHWkdimTJca7oRw”
Set-Cookie:令牌= eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ...; 最大年龄= 3.6; 路径= /; Expires = Fri,28 Sep 2018 05:59:04 GMT; HttpOnly
X-Powered-By:快递

Amu*_*ena 19

是的,您可以通过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
});
Run Code Online (Sandbox Code Playgroud)

或者你也可以试试这个:

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

  • 我试过这种方式,但浏览器一直告诉我`拒绝设置不安全的标题“Cookie”` (3认同)

Aar*_*ron 11

试试看!

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅axios文档:

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

withCredentials的更多详细信息:

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials

  • 有用!我还需要添加 app.use(cors({ credentials: true })); 在快速 API 上。我发现 Ajax 请求会在没有凭据的情况下忽略 CORS 调用中的 Cookie。谢谢@Aaron (7认同)

jno*_*dim 6

如果其他人遇到我遇到的问题,

这是我对类似问题的回答的转贴/sf/answers/4397493971/


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

对我来说,分辨率是设置Access-Control-Expose-Headers标题。

作为解释,从对 axios 存储库中的一个问题的评论中,我被定向到这个人的笔记,这导致我设置了Access-Control-Expose-Headers标题——现在 cookie 在客户端中正确设置。

因此,在 Express.js 中,我必须将exposedHeaders选项添加到我的 cors 中间件中:

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);
Run Code Online (Sandbox Code Playgroud)

同样重要的是,在 axios 方面,我withCredentials在以下 axios 请求中使用配置,以包含 cookie。

前任/

const { data } = await api.get("/workouts", { withCredentials: true });
Run Code Online (Sandbox Code Playgroud)


Nic*_*via 6

我尝试设置withCredentials: true但仍然收到此错误:

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

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

我必须像这样更改 axios 的默认选项:

axios.defaults.withCredentials = true
Run Code Online (Sandbox Code Playgroud)

问题就解决了。没有错误并且 Set-Cookie 按预期工作。