前端自动携带cookie配置
css
let v = document.getElementById("txt").value;
let url = 'http://127.0.0.1/verify';
//axios 携带cookie
const options = {
method: 'POST',
url: url,
headers: {'content-type': 'application/json'},
withCredentials:true,
data: {code: '11'}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
// fetch 携带cookie
const options = {method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: '{"code":"11"}'
};
fetch(url, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
// ajax 携带cookie
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: "application/json",
data:JSON.stringify({'code':v}),
xhrFields: {
withCredentials: true
},
success: function(res){
// 成功处理逻辑
console.log(res)
},
error: function(res){
// 错误时处理逻辑
}
});
}
后端配置
css
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
//允许后端携带的请求头
response.setHeader("Access-Control-Allow-Headers", "X-Custom-Header, Upgrade-Insecure-Requests,Accept,Content-Type, x-requested-with,withCredentials,credentials");
// 是否允许跨源请求携带凭据(如 Cookie、TLS 客户端证书或包含用户名和密码的认证头)
response.setHeader("Access-Control-Allow-Credentials","true");