我已经按照npm包文档的建议写了一个Axios POST请求,比如:

var data = {
    'key1': 'val1',
    'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

它工作,但现在我已经修改了我的后端API接受头文件。

内容类型:“application / json” 授权:“JWT fefege…”

现在,这个请求在Postman上工作得很好,但在编写axios调用时,我遵循了这个链接,但不能完全使其工作。

我经常得到400坏请求错误。

这是我修改后的请求:

axios.post(Helper.getUserAPI(), {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'JWT fefege...'
    },
    data
})      
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

当前回答

我们可以将头信息作为参数传递,

onClickHandler = () => {
  const data = new FormData();
  for (var x = 0; x < this.state.selectedFile.length; x++) {
    data.append("file", this.state.selectedFile[x]);
  }

  const options = {
    headers: {
      "Content-Type": "application/json",
    },
  };

  axios
    .post("http://localhost:8000/upload", data, options, {
      onUploadProgress: (ProgressEvent) => {
        this.setState({
          loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
        });
      },
    })
    .then((res) => {
      // then print response status
      console.log("upload success");
    })
    .catch((err) => {
      // then print response status
      console.log("upload fail with error: ", err);
    });
};

其他回答

在使用Axios时,为了传递自定义标头,需要提供一个对象,其中包含标头作为最后一个参数

修改Axios请求,如下所示:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'JWT fefege...'
}

axios.post(Helper.getUserAPI(), data, {
    headers: headers
  })
  .then((response) => {
    dispatch({
      type: FOUND_USER,
      data: response.data[0]
    })
  })
  .catch((error) => {
    dispatch({
      type: ERROR_FINDING_USER
    })
  })

您还可以使用拦截器来传递头信息

它可以为您节省大量代码

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

拦截器

我也有同样的问题,原因是我没有在拦截器中返回响应。Javascript认为,我想返回undefined的承诺:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

我们可以将头信息作为参数传递,

onClickHandler = () => {
  const data = new FormData();
  for (var x = 0; x < this.state.selectedFile.length; x++) {
    data.append("file", this.state.selectedFile[x]);
  }

  const options = {
    headers: {
      "Content-Type": "application/json",
    },
  };

  axios
    .post("http://localhost:8000/upload", data, options, {
      onUploadProgress: (ProgressEvent) => {
        this.setState({
          loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
        });
      },
    })
    .then((res) => {
      // then print response status
      console.log("upload success");
    })
    .catch((err) => {
      // then print response status
      console.log("upload fail with error: ", err);
    });
};

如果你正在使用vuejs原型中的一些属性,在创建时不能读取,你也可以定义头文件并写入。

storePropertyMaxSpeed(){
  axios
    .post(
      "api/property",
      {
        property_name: "max_speed",
        property_amount: this.newPropertyMaxSpeed,
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + this.$gate.token(),
        },
      }
    )
    .then(() => {
      //this below peace of code isn't important
      Event.$emit("dbPropertyChanged");

      $("#addPropertyMaxSpeedModal").modal("hide");

      Swal.fire({
        position: "center",
        type: "success",
        title: "Nova brzina unešena u bazu",
        showConfirmButton: false,
        timer: 1500,
      });
    })
    .catch(() => {
      Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
    });
};