简体   繁体   English

Axios 发布请求正文未与多路复用服务器解析

[英]Axios post request body not parsing with mux server

I've implemented an API that authenticates users to react clients with Go.我已经实现了一个 API,用于验证用户以使用 Go 响应客户端。 The handler for the authentication route is as follows,身份验证路由的处理程序如下,

func (app *application) authenticate(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        app.clientError(w, http.StatusBadRequest)
        return
    }

    username := r.PostForm.Get("username")
    password := r.PostForm.Get("password")

    fmt.Println(r.PostForm)

    u, err := app.user.Get(username, password)
    if err != nil {
        if errors.Is(err, models.ErrNoRecord) || errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
            app.notFound(w)
        } else {
            app.serverError(w, err)
        }
        return
    }

    token := jwt.New(jwt.SigningMethodHS256)
    claims := token.Claims.(jwt.MapClaims)

    claims["username"] = u.Username
    claims["name"] = u.Name
    claims["exp"] = time.Now().Add(time.Minute * 30).Unix()

    ts, err := token.SignedString(app.secret)
    if err != nil {
        app.serverError(w, err)
        return
    }

    user := models.UserResponse{u.ID, u.Username, u.Name, "Admin", ts}
    js, err := json.Marshal(user)
    if err != nil {
        app.serverError(w, err)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.Write(js)
}

I'm trying to send a post request to the API from the react app using Axios as follows,我正在尝试使用 Axios 从 react 应用程序向 API 发送 post 请求,如下所示,

const data = JSON.stringify({
    username: params.username,
    password: params.password,
});

api.post('/authenticate', data, {
    headers: {'Content-Type': 'application/json' }
}).then(response => {
    console.log(response);
    resolve({ ok: true, json: () => response.data });
}).catch(err => {
    console.log(err);
    reject('Username or password is incorrect');
})

But the request returns a 404 error.但是请求返回 404 错误。 Go console shows that the post data is empty map[] I've tried changing the Content-Type header in the Axios request to multipart/form-data and application/x-www-form-urlencoded with no luck. Go 控制台显示发布数据为空map[]我尝试将 Axios 请求中的 Content-Type 标头更改为multipart/form-dataapplication/x-www-form-urlencoded ,但没有成功。 When the request is made using CURL,当使用 CURL 发出请求时,

curl -d "username=user&password=password" -X POST http://localhost:4000/authenticate

The request returns the proper response.请求返回正确的响应。 Postman is also working fine.邮递员也工作正常。 What could be the possible issue that the request body is not parsed in Go when only the request is made from Axios?当仅从 Axios 发出请求时,在 Go 中未解析请求正文的可能问题是什么?

Working solution is using the package qs to stringify data.工作解决方案是使用包qs来字符串化数据。

import qs from 'qs';

const data = {
    username: params.username,
    password: params.password,
};

api.post('/authenticate', qs.stringify(data)
).then(response => {
    console.log(response);
    resolve({ ok: true, json: () => response.data });
}).catch(err => {
    console.log(err);
    reject('Username or password is incorrect');
})

Try to use FormData.尝试使用 FormData。

const data = new FormData();
data.set('username', params.username);
data.set('password', params.password);

In your client request, you are sending a JSON body;在您的客户端请求中,您正在发送一个 JSON 正文; however on the server you're expecting url-encoded values.但是在服务器上,您需要 url 编码的值。

You should either change your client to send the correct data, eg like this , or you need to accept the JSON body by parsing it with the encoding/json package on the server side.您应该更改您的客户端以发送正确的数据,例如像这样,或者您需要通过在服务器端使用encoding/json包解析它来接受 JSON 正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM