Home > Web Front-end > JS Tutorial > body text

How to implement cookie cross-domain in axios

亚连
Release: 2018-06-19 16:04:34
Original
5227 people have browsed it

Since joining Vue, I have been using the axios library to make some asynchronous requests. The following article mainly introduces you to the relevant information about cookie cross-domain and related configuration in Axios. The article introduces it in great detail through sample code. Friends in need can refer to it. Let’s take a look together.

Preface

Recently I have encountered some minor problems in the aspects of cross-domain, cookie and form upload. Let me make a brief exploration and summary. . This article mainly introduces the relevant content about cookie cross-domain and related configuration in axios. I won’t say much below, let’s take a look at the detailed introduction.

1. Request with cookie - highlight the key points

axios does not bring cookies by default when sending a request, you need to set it up withCredentials: true to solve. At this time, you need to pay attention to the back-end settings:

  • header informationAccess-Control-Allow-Credentials:true

  • Access-Control-Allow-Origin cannot be '*', because '*' will conflict with Access-Control-Allow-Credentials:true, and the specified address needs to be configured

If End settingsAccess-Control-Allow-Origin: '*' , there will be the following error message

Failed to load http://localhost:8090/category/lists: 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'. Origin 'http://localhost:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Copy after login

The backend configuration is indispensable, otherwise an error will occur. Paste my backend example :

const express = require('express')
const app = express()
const cors = require('cors') // 此处我的项目中使用express框架,跨域使用了cors npm插件
app.use(cors{
   credentials: true, 
   origin: 'http://localhost:8081', // web前端服务器地址
   // origin: '*' // 这样会出错
  })
Copy after login

After success, you can see in the request

2. The axios configuration of my front-end project code

The unified configuration of axios will greatly improve efficiency, avoid bugs, and locate bugs (to facilitate the capture of error information)

Create a separate fetch.js to encapsulate axios requests and expose them as methods

import axios from 'axios'
// 创建axios实例
const service = axios.create({
 baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
 timeout: 5000, // 请求的超时时间
 //设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
 // headers: { 
 // "Content-Type": "application/x-www-form-urlencoded"
 // },
 withCredentials: true // 允许携带cookie
})
// 发送请求前处理request的数据
axios.defaults.transformRequest = [function (data) {
 let newData = ''
 for (let k in data) {
 newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
 }
 return newData
}]
// request拦截器
service.interceptors.request.use(
 config => {
 // 发送请求之前,要做的业务
 return config
 },
 error => {
 // 错误处理代码
 
 return Promise.reject(error)
 }
)
// response拦截器
service.interceptors.response.use(
 response => {
 // 数据响应之后,要做的业务
 return response
 },
 error => {
 return Promise.reject(error)
 }
)
export default service
Copy after login

As shown below, if you need to call ajax request

import fetch from '@/utils/fetch'
fetch({
 method: 'get',
 url: '/users/list'
})
 .then(res => {
 cosole.log(res)
})
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use keep-alive in vue2

There are environment configurations about jquery plug-in in webpack ( Detailed tutorial)

How to implement paging query in Bootstrap4 Vue2

The above is the detailed content of How to implement cookie cross-domain in axios. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template