登录
首页 >  Golang >  Go问答

如何从 Axios、React 解组 json 请求

来源:stackoverflow

时间:2024-03-07 15:54:26 151浏览 收藏

大家好,我们又见面了啊~本文《如何从 Axios、React 解组 json 请求》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我正在 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));
  }

解决方案


当您使用 axios 进行 post 请求时,一种方法是

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"
  });

终于介绍完啦!小伙伴们,这篇关于《如何从 Axios、React 解组 json 请求》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>