我已经按照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})
})

在使用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的完整示例。使用自定义报头发布请求

var postData = { 电子邮件:“test@test.com”, 密码:“密码” }; let axiosConfig = { 标题:{ “内容类型”:“application / json; charset = utf - 8”, “Access-Control-Allow-Origin”:“*”, } }; axios。post('http://<主机>:<端口>/<路径>',postData, axiosConfig) .then((res) => { console.log("RESPONSE RECEIVED: ", res); }) .catch((err) => { console.log("AXIOS ERROR: ", err); })

舒布哈姆的回答对我不起作用。

在使用Axios库并传递自定义头信息时,需要将头信息构造为具有键名‘headers’的对象。'headers'键应该包含一个对象,这里是Content-Type and Authorization。

下面的示例运行良好。

var 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})
    })

如果你正在使用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");
    });
};

Const data = { 电子邮件:“me@me.com”, 用户名:“我” }; Const选项= { 标题:{ “内容类型”:“application / json”, } }; axios。post('http://path',数据,选项) .then((res) => { console.log("RESPONSE ====: ", res); }) .catch((err) => { console.log("ERROR: ====", err); })

所有超过400的状态代码都将被Axios捕获块捕获。

同样,对于Axios中的post方法,头是可选的

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

它可以为您节省大量代码

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;
});

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

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 POST请求中设置标头,请将第三个对象传递给Axios . POST()调用。

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

要在Axios GET请求中设置标头,请将第二个对象传递给Axios . GET()调用。

const token = '..your token..' 

axios.get(url, {
  headers: {
    'Authorization': `Basic ${token}`
  }
})

拦截器

我也有同样的问题,原因是我没有在拦截器中返回响应。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);
  });

axios。Post可以接受3个参数,最后一个参数可以接受一个配置对象,可以设置头。

示例代码与您的问题:

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