Как отменить запрос JSON от Axios, React - PullRequest
0 голосов
/ 12 ноября 2018

Я работаю над REST-связью между веб-интерфейсом React и внутренним интерфейсом Go, у меня проблема с отправкой правильного http-запроса. Если я использую curl, все работает нормально, но когда я использую axios, я получаю пустую структуру (unmarshalling не возвращает ошибку). Мне кажется, что сгенерированные запросы должны быть точно такими же.

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 голосов
/ 13 ноября 2018

Когда вы делаете пост-запрос с помощью axios, один из способов сделать это -

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

, если вы хотите, вы также можете добавить операторы здесь.

else

axios.post('http://localhost:8000/api/rooms/signin', {
 headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'JWT fefege...'
                },
             "username": "Username", 
             "password": "Password"
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...