question
Axios sends request request header information does not contain Cookie information
detailed question
Use Vue+SpringBoot for project development, axios for network requests, send requests, and the request header information does not contain Cookie information The details are
as follows
Actual effect
Expected effect
solution
scope
Vue project global configuration
Open the entry file of the Vue project (usually main.js) → \rightarrow→ Add the following configuration
import axios from 'axios';
axios.defaults.withCredentials = true;
For the author, that is
Components or views configuration in Vue project
Open the components or views file in the Vue project → \rightarrow→在components或views中的 < S c r i p t > < / S c r i p t > <Script></Script> <Script></Script> Add the following configuration in the header
import axios from 'axios';
axios.defaults.withCredentials = true;
For the author, that is
Under the request method in components or views in the Vue project
Find the request method in the components or views in the Vue project → \rightarrow→ Add the following configuration to the method
axios.get('/api/data', {
withCredentials: true
})
.then(response => {
// 处理响应数据
})
.catch(error => {
// 处理错误
});
For the author, that is
cause
The reason for the problem is that the request header information sent by axios does not contain cookies due to the limitation of cross-domain requests. Specifically, in the browser's security policy, cookies are not sent by default for cross-domain requests. Cross-domain requests refer to the inconsistency between the domain where the front-end code resides and the domain where the back-end API resides, including differences in domain names, ports, or protocols. Due to security considerations, browsers will prevent cross-domain requests from carrying cookies by default to prevent potential security risks.
solve the cause
In the front-end project, by configuring the withCredentials attribute of axios to true, tell axios to carry cookies in cross-domain requests. Can be set in global configuration, component-level configuration, or individual request methods.
Global configuration: set axios.defaults.withCredentials = true in the entry file of the Vue project (such as main.js), so that all axios requests carry cookies. Component-level configuration: <script> <script>
in the component<script> Introduce axios in the tag, and set axios.defaults.withCredentials = true, so that all axios requests in this component will carry cookies.
Single request method configuration: In a specific axios request method, set the request to carry Cookie separately through the configuration item withCredentials: true.
references
Causes and solutions refer to chatgpt
It’s not easy
to be original, please indicate the source
if it’s helpful to you, don’t forget to like it and support it