【问题标题】:React js Axios callReact js Axios 调用
【发布时间】:2020-04-05 10:08:17
【问题描述】:

我对 React 还很陌生,我似乎无法使用 Axios 成功调用外部 API

外部API的指导方针是:

请求(如果我们知道所有参数)

{
  "service": "login",
  "username": "john",
  "password":"aitis",
  "appId": "2001",
  "COMPANY": "1000",
  "BRANCH": "1000",
  "MODULE": "0",
  "REFID": "1",
  ---- optional ---
  "LOGINDATE": "2017-12-31 13:59:59",
  "TIMEZONEOFFSET": -120
}

回应

{
    "success": true,
    "clientID": "Wj8Te8EqWghDM.........   .....wYGtzlyc1At%2bPrG8t"
}

我的代码是:

componentDidMount() {

    axios.get('http://...serverurl....', {
      params: {
        service: 'login',
        username: 'john',
        password: 'aitis',
        appID: '2001',
        company: '1000',
        branch: '1000',
        module: '0',
        refid: '1'
      },
       headers: {
         'accept': 'application/json',
         'Access-Control-Allow-Origin': '*',
         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
       }
    })
    .then(response => console.log(response));
  }

我没有得到 clientID 响应,而是得到了这个: Response

{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
data:
success: false
errorcode: 0
error: "JSON Object must begin with "{" at character 2 of service=login&username=john&password=aitis&appID=2001&Company=1000&Branch=1000&Module=0&Refid=1 JSON Syntax Error : at charact↵
 error on character : 2"
__proto__: Object
status: 200
statusText: ""
...

我的电话有问题吗?

提前致谢。

【问题讨论】:

  • 你得到了 200 个代码响应,所以请求看起来没问题,看看服务器如何匹配请求的 params 对象
  • 真的需要headers吗?
  • 我试过没有它们,结果相同
  • 你的axios调用不正确,你只是调用'url',你需要将它实际替换为真实的URL,如果它保存在一个url变量中,它应该是${url}
  • 对不起。我应该澄清一下,我用真实的 url 替换了 'url'

标签: reactjs axios


【解决方案1】:

如果要发送带有这些参数的 GET 请求,请在 URL 中设置这些参数

const URL = `${baseURL}/url?service=login&username=jhon&password=aitis&appID=2001&company=1000&branch=1000&module=0&refid=1`;
axios.get(URL).then(response => console.log(response));

【讨论】:

    【解决方案2】:

    我想通了。我不得不使用 axios.post 而不是 axios.get。

    非常感谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2017-07-18
      • 2020-08-21
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多