ChatGPT解决这个技术问题 Extra ChatGPT

使用 axios POST 请求传递标头

我已经按照 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 调用时,我遵循 this link 并不能完全让它工作。

我经常收到 400 BAD Request 错误。

这是我修改后的请求:

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

S
Sabito 錆兎 stands with Ukraine

使用 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
    })
  })

@KishoreJethava,500 是内部服务器错误,您能否在服务器端检查标头是否出现或是否存在其他错误
@KishoreJethava,你能在你的服务器中记录标题,看看你是否得到了正确的值
你不需要发布任何数据吗?还要确保 this.state.token 包含一个值
@ShubhamKhatri,我可以请您在这里查看一个与 axios 相关的问题:stackoverflow.com/questions/59470085/… 吗?
S
Sabito 錆兎 stands with Ukraine

以下是带有自定义标头的 axios.post 请求的完整示例

var postData = {电子邮件:“test@test.com”,密码:“密码”};让 axiosConfig = { headers: { 'Content-Type': '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); })


面对这个问题获取请求。响应以 xml 格式出现。这并不能解决问题。
为此,您需要添加 headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" } 请注意,这仅在您的 api 支持 json 响应时才有效
S
Sabito 錆兎 stands with Ukraine

要在 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}`
  }
})

S
Sabito 錆兎 stands with Ukraine

常量数据 = { 电子邮件:“me@me.com”,用户名:“我”}; const options = { headers: { 'Content-Type': 'application/json', } }; axios.post('http://path', data, options) .then((res) => { console.log("RESPONSE ==== : ", res); }) .catch((err) = > { console.log("错误: ====", err); })

所有高于 400 的状态码都会被 Axios 的 catch 块捕获。

此外,标题对于 Axios 中的 post 方法是可选的


I
Israel kusayev

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

它可以为您节省大量代码

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

我建议使用 config.method.toUpperCase()
不幸的是,我的较低
S
Sabito 錆兎 stands with Ukraine

Shubhamanswer 对我不起作用。

当您使用 Axios 库并传递自定义标头时,您需要将标头构造为具有键名称“headers”的对象。 'headers' 键应该包含一个对象,这里是 Content-TypeAuthorization

下面的例子工作正常。

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

S
Sabito 錆兎 stands with Ukraine

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

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

S
Sabito 錆兎 stands with Ukraine

axios.post 可以接受 3 个参数,最后一个参数可以接受一个可以设置标头的 config 对象。

您的问题的示例代码:

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

S
Sabito 錆兎 stands with Ukraine

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

S
Sabito 錆兎 stands with Ukraine

拦截器

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