Axios and Cookie Operation

本文探讨了使用Axios进行跨域请求时的操作Cookie方法,包括设置与获取Cookie的具体实现,以及服务器端如何配置以支持CORS。通过示例代码展示了如何在Node.js客户端上正确读取和设置Cookie。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Axios and Cookie Operation

My current service, response with the headers as follow:
Connection: keep-alive
Content-Language: en
Content-Length: 274
Content-Type: application/json; charset=utf-8
Date:
Server: Apache
Vary: Authorization, Accept-Language, Cookie

The Demo Header Service is as follow, the URL is http://httpbin.org/headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 528
Content-Type: application/json
Date:
Server: gunicorn/19.9.0
Via: 1.1 vegur

Some Keep Details about operations on Cookie from Axios
Some sample is as follow:
axios.request({
method: "get",
url: uri,
headers: headers,
params: params,
maxRedirects: 0,
validateStatus: function(status) {
return status >= 200 && status < 303;
},
withCredentials: true,
}).then(response => {
console.log("cookie:" + response.headers["set-cookie"]);
return resolve(response.data);
}).catch((error:any) => {
console.error(error);
return reject();
});
});
}

https://stackoverflow.com/questions/36365409/setting-cookies-with-cors-requests
On the server side, it should support these:
res.writeHead(200, {
’Set-Cookie’: ‘’,
‘Access-Control-Allow-Origin’: ‘http://sillycat.ddns.net:8383',
‘Access-Control-Allow-Credentials’: ’true’,
‘Access-Control-Allow-Methods’: ‘GET, POST’,
‘Access-Control-Allow-Headers’: ‘Content-Type, Set-Cookie, *'
});

In general, if the server side does not support CORS, the nodeJS client can not get the headers[’set-cookie’]. The browser can, postman can, but I fails to do that in NodeJS client without CORS.

References:
https://stackoverflow.com/questions/48846653/get-cookie-from-axios-response-using-cors-on-the-server-side
https://github.com/axios/axios/issues/92
https://github.com/axios/axios/issues/295
https://github.com/axios/axios/issues/953
https://stackoverflow.com/questions/48846653/get-cookie-from-axios-response-using-cors-on-the-server-side
### 解决 JHipster 中 401 Unauthorized 错误的方法 当遇到 `401 Unauthorized` 错误时,通常表示客户端尝试访问受保护的资源而未提供有效的认证凭证。以下是针对路径 `/operation/app/callback/we-com/index.html` 的解决方案。 #### 背景分析 HTTP 请求中的查询字符串可能包含潜在的安全风险,因此其内容应被视为不安全[^1]。如果请求到达服务器端并触发了未经授权的错误,则可能是由于缺少必要的身份验证令牌或会话信息所致。此外,在处理回调函数时,良好的实现可以提高应用程序的健壮性和性能[^2]。 #### 技术细节与解决方法 为了修复此问题,可以从以下几个方面入手: 1. **检查 Token 或 Cookie** 验证是否已向客户端发送适当的身份验证 token(如 OAuth2 access_token)。如果没有设置或者已经过期,则需要重新登录获取新的 token。 2. **配置 Security Filters** 如果使用的是 Spring Boot 和 Spring Security 组合开发的应用程序,那么可以通过调整 security filters 来允许特定 URL 不经过身份验证即可访问。例如修改 WebSecurityConfigurerAdapter 子类如下所示: ```java @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/operation/app/callback/**").permitAll() // Allow all requests to this path without authentication. .anyRequest().authenticated(); } ``` 3. **前端重定向逻辑优化** 当接收到状态码为 401 的响应时,应该引导用户至登录页面而不是显示空白页或其他错误提示。这一步骤可通过拦截器完成,比如 AngularJS 应用中可定义 `$httpProvider.interceptors.push('authInterceptorService');` 并在服务内部捕获异常进行相应操作。 4. **日志记录增强** 增强应用的日志功能可以帮助快速定位问题所在位置以及原因。确保每次失败请求都被详细记录下来以便后续排查。 通过上述措施能够有效减少甚至消除因权限不足而导致的服务拒绝现象发生几率。 ```javascript // Example JavaScript code snippet demonstrating how you might handle unauthorized responses on client side using Axios library. axios.interceptor.response.use(null, function(error){ const originalRequest = error.config; if (error.response.status === 401 && !originalRequest._retry){ originalRequest._retry = true; return axios.post('/auth/refresh-token').then((response)=>{ localStorage.setItem('token', response.data.token); originalRequest.headers['Authorization'] = 'Bearer '+localStorage.getItem('token'); return axios(originalRequest); }); } throw error; }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值