axios跨域请求设置并携带Cookies

axios跨域请求设置Cookies

书接上回:《axios转发/oauth/authorize未设置cookies问题》
上回实现了axios 在client域名下情趣oauth域名并使response返回Set-Cookies的header
在这里插入图片描述
但是,接下来在域名oauth.szile.com域名下请求接口时,请求没有携带设置的Cookie,这是问什么? 难道是没有设置成功?
在这里插入图片描述
查看Application下Cookie,确实是没有设置成功。
在这里插入图片描述
经过搜索查找说 axios的请求必须配置axios.defaults.withCredentials = true,并且Response的Header需要有Access-Control-Allow-Credentials: true。

配置axios

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 0, // 请求超时时间
  withCredentials: true
})
// 或者
// axios.defaults.withCredentials = true;

Response header中写返回了
在这里插入图片描述
但却报跨域错误
在这里插入图片描述
在这里插入图片描述
从console信息「The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard '’ when the request’s credentials mode is ‘include’.」时说当请求是携带凭据模式(即Access-Control-Allow-Credentials: true、携带Cookie)时,Response的header “Access-Control-Allow-Origin” 的值不能是“” 通配符。

经过需改配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {

    // *** 此处省略 *** 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(httpServletRequest -> {
            final CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowedOrigins(List.of("*"));
            corsConfiguration.setAllowedHeaders(List.of("*"));
            corsConfiguration.setAllowCredentials(true);

            return corsConfiguration;
        });
        // *** 此处省略 *** 
    }
}   

成功的设置Cookie
在这里插入图片描述
在这里插入图片描述

总结

  1. 跨域请求是携带Cookie ,需要配置axios.defaults.withCredentials = true;
  2. 响应需要携带响应头 Access-Control-Allow-Credentials: true;
  3. 响应头 Access-Control-Allow-Origin 不能是通配符“*” ,并且需要和请求头Origin 的值一致。
  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Vue中使用Axios发送请求时,可以通过设置`withCredentials`选项来携带cookie。`withCredentials`选项是一个布尔值,如果设置为`true`,则表示发送跨域请求携带cookie。 以下是一个示例代码: ```javascript import axios from 'axios'; axios.defaults.withCredentials = true; axios.get('/api/user', { headers: { 'Content-Type': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ``` 在上面的示例中,我们设置了`axios.defaults.withCredentials`为`true`,这样所有的请求都会自动携带cookie。然后发送一个GET请求,指定请求头为`Content-Type: application/json`,然后处理响应。 需要注意的是,如果服务端没有设置允许跨域请求携带cookie,那么即使客户端设置了`withCredentials`为`true`,cookie也不会被发送。因此,在开发时需要确认服务端是否设置了允许跨域请求携带cookie。 ### 回答2: Vue是一个JavaScript库,用于构建用户界面。Axios是一个基于Promise的HTTP库,用于与后端进行HTTP通信。 要在Vue中使用Axios携带cookie,可以按照以下步骤进行设置: 1. 安装Axios:首先,在Vue项目中安装Axios。可以使用npm或者yarn来安装。在终端中运行以下命令: ``` npm install axios ``` 2. 引入Axios:在需要使用Axios的组件中,引入Axios库。在Vue组件的script标签中添加以下代码: ``` import axios from 'axios' ``` 3. 创建Axios实例:为了能够全局使用Axios,可以在Vue的根组件中创建一个Axios实例,并设置`withCredentials`为`true`。在Vue实例的生命周期函数`created`中添加以下代码: ``` created() { // 创建Axios实例 this.$http = axios.create({ withCredentials: true // 允许发送跨域请求携带cookie }); } ``` 4. 发送请求:使用`this.$http`来发送请求。可以使用Axios的各种请求方法发送GET、POST等请求,并可以在请求中携带cookie。例如,在Vue组件的某个方法中添加以下代码: ``` this.$http.get('https://example.com/api/data') .then(response => { // 处理返回的数据 }) .catch(error => { // 处理请求错误 }) ``` 通过以上步骤,就可以在Vue中使用Axios携带cookie了。设置`withCredentials`为`true`允许发送跨域请求携带cookie,这样可以实现与后端进行HTTP通信并在请求中携带cookie。 ### 回答3: 在Vue中使用Axios发送请求时,可以通过设置`withCredentials`属性来携带cookie。 首先,确保你的Vue项目已经安装了Axios依赖。然后,在发送请求前,需要先导入Axios库,并创建一个Axios实例。可以在Vue的`main.js`文件中进行全局配置。 ```javascript // main.js import Axios from 'axios' Vue.prototype.$axios = Axios.create({ withCredentials: true, // 开启携带cookie }) ``` 现在,在需要发送请求的组件中,可以直接使用`this.$axios`来发送带有cookie的请求。例如,在一个登录页面中,可以发送一个POST请求来验证用户登录信息,并在请求头中携带cookie。 ```javascript // Login.vue methods: { login() { const data = { username: this.username, password: this.password, } this.$axios.post('/api/login', data).then(response => { // 处理响应 }).catch(error => { // 处理错误 }) } } ``` 在上面的例子中,`/api/login`是后端登录接口的URL。在发送POST请求时,`withCredentials`属性会自动将浏览器中的cookie发送到服务器。 需要注意的是,为了确保cookie的正确发送,后端服务器的响应头也需要设置为允许携带cookie。可以在后端代码中添加以下代码: ```javascript // Express.js 示例 const express = require('express') const app = express() app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:8080') // 设置允许的来源地址 res.header('Access-Control-Allow-Credentials', true) // 允许携带cookie next() }) // 处理其它路由 ``` 以上就是使用Vue和Axios携带cookie的方法。通过设置`withCredentials`为`true`,可以确保请求中带有cookie,并且后端服务器的响应头也需要允许携带cookie。这样就可以在Vue项目中实现带有cookie的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超人@不会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值