如何解组来自Axios,React

时间:2018-11-12 19:42:26

标签: reactjs go

我正在React前端和Go后端之间进行REST通信,我在发送适当的http post请求时遇到问题。如果我使用curl,一切都可以正常工作,但是当我使用axios时,我得到的是一个空结构(解组不会返回错误)。在我看来,生成的请求应该完全相同。

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "encoding/json"
    "io/ioutil"
)

type Credentials struct {
    Password string `json:"password", db:"password"`
    Username string `json:"username", db:"username"`
}

func main() {
    fmt.Println("Listening on port 8000")

    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/api/rooms/signin", Signin)

    log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

    if r.Method == "OPTIONS" {
        return
    }
    if r.Method == "POST" {
        // Read body
        b, err := ioutil.ReadAll(r.Body)
        defer r.Body.Close()
        if err != nil {
            fmt.Println("Couldn't read request body")
            http.Error(w, err.Error(), 500)
            return
        }

        // Unmarshal
        var creds Credentials
        err = json.Unmarshal(b, &creds)
        if err != nil {
            fmt.Println("Couldn't unmarshal body")
            http.Error(w, err.Error(), 500)
            return
        }
        fmt.Println(creds)

        fmt.Println("username:", creds.Username)
        fmt.Println("password:", creds.Password)

        w.WriteHeader(http.StatusOK)
        return
    }
}

我的curl命令:

curl -X POST -H "Content-Type: application/json" -d '{"username":"Username","password":"Password"}' "http://localhost:8000/api/rooms/signin"

反应处理程序:

  handleSubmit = (event) => {
    event.preventDefault();
    var data = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: {
            "username": "Username", 
            "password": "Password",
        }
    };
    axios.post('http://localhost:8000/api/rooms/signin', data)
        .then(response => {
            console.log(response);
        })
        .catch(error => console.log(error));
  }

1 个答案:

答案 0 :(得分:1)

使用axios进行发布请求时,一种方法是

axios({
  method: 'post',
  url: 'http://localhost:8000/api/rooms/signin',
  data: {
         "username": "Username", 
         "password": "Password"
  },
config: { headers: {'Content-Type': 'application/json' }}
});

如果需要,也可以在此处添加then语句。

其他

axios.post('http://localhost:8000/api/rooms/signin', {
 headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'JWT fefege...'
                },
             "username": "Username", 
             "password": "Password"
  });