首页 > 解决方案 > NodeJS 中的 Axios 发布请求

问题描述

我在 POSTMAN 中有一个 API 调用,我正在尝试使用 Axios 在 nodeJS 项目中复制它,但结果与 POSTMAN 不同。

POSTMAN 中的调用如下所示: 邮递员 API 调用

在我的 body 元素内部:模型​​和值属性和 Authorization 是 Bearer 类型。

我得到一个数组的响应结果。

现在,我尝试使用 axios 做同样的事情,但出现错误:

代码

axios.defaults.baseURL = 'http://XXXXXXXXXXXXXXX:8069/api';

axios({
  method: 'POST',
  url: '/create/res.users', 
  data: {
    models: 'res.users',
    values: "{ 'login': 'john@gmail.com', 'name':'john', 'email':'john@gmail.com', 'password': '123123123' }"
  },
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + accessToken
  },
})
.then(function (response) {

  console.log("Register", response);
  res.status(200).send({
    message: response.data
  });

})
.catch(function (error) {

  console.log("Error", error.response.data);
  res.status(error.response.status).send({
    message: error.response.data
  });

});

错误

{
    "message": {
        "name": "odoo.exceptions.RedirectWarning",
        "message": "You cannot create a new user from here.\n To create new user please go to configuration panel.\n74\nGo to the configuration panel",
        "arguments": [
            "You cannot create a new user from here.\n To create new user please go to configuration panel.",
            74,
            "Go to the configuration panel"
        ],
        "exception_type": "error",
        "code": 500,
        "description": "Restful API Error"
    }
}

标签: node.jsexpressaxios

解决方案


默认情况下,axios 将 JavaScript 对象序列化为 JSON。要改为以 application/x-www-form-urlencoded 格式发送数据,本文档可能会帮助您:

https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format


推荐阅读