Axios获取请求将无法工作,但发布请求可以吗?

时间:2019-10-04 04:45:12

标签: reactjs rest

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {



  handleSubmit(event) {
    axios.get('http://localhost:3050/login', {
      "username": "username",
      "password": "password"
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }

  render() {

      return(

        <form onSubmit={this.handleSubmit}>
          <input type="submit" value="Submit" />
        </form>

      );
  }

}

export default App;

在邮递员中,给定GET请求,并根据需要在此输入json

{
    "username": "username",
    "password": "password"
}

响应正文为200,然后返回

{ 
    "friends": 0,
    "id": "555"
}

当我单击“尽管反应时提交”时出现此错误

Error: Request failed with status code 400
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

如果我将后端更改为POST并发送axios.post,它将起作用。我不知道。有人知道吗?用axios发送获取请求,您需要做些其他事情吗?

4 个答案:

答案 0 :(得分:1)

如何在GET请求中发送JSON。在GET中,您可以在path或query参数中发送值。如果您发送正文,则它将无法正常工作。 最佳做法是,如果要发送内容,请使用POST调用而不是GET。

答案 1 :(得分:0)

如果要将查询字符串参数添加到get请求中,则需要像这样调用axios:

axios.get("http://localhost:3050/login", {
  "params": {
    "username": "username",
    "password": "password"
  }
})

请注意,axios.get和axios.post接受不同的参数:

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])

不能将.get.post与相同的参数互换使用。

您所点击的API可能也不会通过其GET API接受用户名和密码。

答案 2 :(得分:0)

您正在发出axios获取请求, 您可以通过两种方式将参数传递给您的请求

axios.get('http://localhost:3050/login?username='username'&password='password')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

或者您可以传递这样的参数

axios.get('http://localhost:3050/login', {
  params: {
   username: "username",
   password: "password"
   }
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

参考:Axios 希望对您有帮助

答案 3 :(得分:0)

嗨,尝试用jsonplaceholder进行操作,然后在标题Json中进行选择:) 在服务器端console.log(req.body) 最后,请const body = username, passport 来自州