axios跨域发请求携带X-Requested-With,后端判断是否ajax请求

提示:跨域不携带 X-Requested-With 请求头,通过 accept请求头,也可以判断是否 ajax请求,详见:判断是否ajax请求原理

说明

X-Requested-With 请求头,后端用于判断该请求是否 ajax 请求

jquery 默认发送,但 axios 默认不发送,需要指定

跨域 携带 X-Requested-With 头

关键代码

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

例子

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.post('http://localhost:8080/RegCtrl', 
  this.form
)
.then(function (res) {
  console.log(res);
})
.catch(function (error) {// 请求失败处理
  console.log(error);
});

后端处理

Access-Control-Allow-Headers 头需要有 X-Requested-With 值

关键代码:

response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");

后端例子

详见 链接


原文出处:/show_1IX46ZsMmg8T.html