How to implement cookie cross-domain in axios
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 information
Access-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.
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: '*' // 这样会出错 })
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
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) })
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

In our daily use of computers and the Internet, we are often exposed to cookies. A cookie is a small text file that saves records of our visits to the website, preferences and other information. This information may be used by the website to better serve us. But sometimes, we need to find cookie information to find the content we want. So how do we find cookies in the browser? First, we need to understand where the cookie exists. in browser

Solutions for document.cookie not being obtained: 1. Browser privacy settings; 2. Same-origin policy; 3. HTTPOnly Cookie; 4. JavaScript code error; 5. Cookie does not exist or expires; 6. Cross-domain issues; 7. Viewer mode; 8. Server problems; 9. JavaScript execution timing; 10. Check console log, etc.
