阻止 axios 发送选项请求

问题描述

我正在发送 axios post 请求,但浏览器首先发送选项请求。为了防止这种情况发生,我创建了一个如下所示的配置对象:

const config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};

在我的应用程序的一部分中,这非常有效。这是:

await this.$http.post("/editJob",this.job,config).then(response =>{
          let job = response.data;
          if(job){
            job = Job.convertObject(job);
            this.$store.commit("editJob",job);
          }
        }).catch(err =>{
          console.log(err);
          this.errMessages.push("There was a problem editing the Job. Contact your administrator.");
        })

但是在我发送稍微复杂的 JS 对象的应用程序的不同部分,它仍然发送选项请求。这是:

 await this.$http.post("/addUser",this.user,config).then(response =>{
          let user = User.convertObject(response.data);
          if(user){
            this.$store.commit("addUser",user);
          }else{
            this.errMessages.push("Unable to add the Employee. Please contact your administrator.");
          }
        }).catch(err =>{
          console.log(err);
          this.errMessages.push("Unable to add the Employee. Please contact your administrator.");
        });

后端清楚地记录了第二种情况下的 OPTION 请求,但我看不出 axios 调用有什么不同。我目前不知所措。如果有人有任何建议,请提前告诉我并致谢。

迈克

解决方法

这是一个预检请求。

防止预检请求的解决方案是设置头Access-Control-Max-Age。

Access-Control-Max-Age 响应头指示预检请求的结果(即包含在 Access-Control-Allow-Methods 和 Access-Control-Allow-Headers 头中的信息)可以缓存多长时间.

您可以找到有关它的更多信息here