当 Vue 使用 axios 发起请求时,如果请求没有携带 cookie 信息,可能是由于以下几个原因导致。
如果请求的目标服务器与当前页面的域名不同,浏览器默认不会发送 cookie。解决此问题可以在请求头中设置 withCredentials: true,表示允许发送 cookie。例如:
axios.get('http://example.com/api/data', {
withCredentials: true
});如果目标服务器未设置 Access-Control-Allow-Credentials: true 响应头,浏览器也不会发送 cookie。需要确保服务器设置了该响应头。
在 Node.js 中使用 Express 框架设置,如:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://example.com');
res.header('Access-Control-Allow-Credentials', true);
next();
});httpResponse.setHeader("Access-Control-Allow-Origin", "http://example.com");
// 如果要把Cookie发到服务器,需要指定 Access-Control-Allow-Credentials 字段为 true
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");location / {
add_header Access-Control-Allow-Origin http://example.com;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 添加映射路径
registry.addMapping("/**")
.allowedOriginPatterns("http://example.com") // 放行哪些域名,可以多个
.allowCredentials(true) // 是否发送Cookie信息
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH") // 放行哪些请求方式
.allowedHeaders("*") // 放行哪些原始域(头部信息)
.exposedHeaders("Header1", "Header2") // 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.maxAge(3600); // 预请求的结果有效期,默认1800分钟,3600是一小时
}
};
}
}如果目标服务器未设置 Access-Control-Allow-Origin 响应头,浏览器也不会发送 cookie。需要确保服务器设置了正确的 Access-Control-Allow-Origin 响应头,允许请求的来源域名。例如,在Node.js中使用Express框架:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://example.com');
res.header('Access-Control-Allow-Credentials', true);
next();
});更多设置方式,请参考原因二。