Home  >  Article  >  Backend Development  >  Issues receiving Axios post data from Reactjs application using Golang

Issues receiving Axios post data from Reactjs application using Golang

王林
王林forward
2024-02-06 08:39:08522browse

使用 Golang 从 Reactjs 应用程序接收 Axios 发布数据时出现问题

Question content

I have a locally hosted webpage using reactjs which sends axios posts to port 9000. I have a golang server listening to the port and receiving the post. It then decodes the post but never gets any data. Below is the code part for sending axios post in reactjs application.

onsubmit = (event) => {
        event.preventdefault();
        let { task } = this.state;
        console.log("printing new task title:", task);
        if (task) {
            axios
            .post(
                endpoint + "/api/task",
                {task},
                {headers: {"content-type": "application/x-www-form-urlencoded"}}
            )
            .then((res) => {
                this.gettasks();
                this.setstate({task: ""});
                console.log(res);
            });
        }
    };

The following is the part of the golang server that processes posts.

// createtask create task route
func createtask(w http.responsewriter, r *http.request) {
    w.header().set("context-type", "application/x-www-form-urlencoded")
    w.header().set("access-control-allow-origin", "*")
    w.header().set("access-control-allow-methods", "post")
    w.header().set("access-control-allow-headers", "content-type")
    var newtask listitem
    _ = json.newdecoder(r.body).decode(&newtask)
    fmt.println(newtask)
    insertonetask(newtask)
    json.newencoder(w).encode(newtask)
}

The following is the listitem structure

type listitem struct {
id        primitive.objectid `json:"_id,omitempty" bson:"_id,omitempty"`
title     string             `json:"title,omitempty"`
completed bool               `json:"completed,omitempty"`
}

I tried renaming it to title instead of task and just passing static variables but to no avail.

In the console it prints the entered text correctly, but when the console outputs the axios response from the golang server, its response never contains the task name.

This is an example of the response data part from the golang server: data: {_id: '0000000000000000000000000', title:'test'}.

It only outputs this data: {_id: '000000000000000000000000'}

After receiving the post, the golang terminal output is as follows:

{ObjectID("000000000000000000000000")  false}
Inserted a Single Record  ObjectID("63decde2a336b8e7cdc2b865")

The task properties appear to be in the new .My problem is that the new task does not have the text entered from the web page. If you need more code, please see the code below

  • Main Repository
  • reactjs file
  • go main file

Correct answer


It is recommended to use devtools to debug such problems.

Screenshot shows the payload is form url encoded. But the server tries to read it using json decoder (_ = json.newdecoder(r.body).decode(&newtask)). If you don't ignore the decode error, it should report that the content is not valid json. To resolve this issue, simply remove {headers: {"content-type": "application/x-www-form-urlencoded" from client/src/to-do-list.js "}} That's it.

After the change, the payload will be:

Other errors:

1. context-type The header does not match the content in the response

The func

createtask in go-server/main.go also has another problem. The response is encoded as json:

json.newencoder(w).encode(newtask)

Conflicts with:

    w.header().set("context-type", "application/x-www-form-urlencoded")

The title should be replaced with:

w.header().set("context-type", "application/json")

2. cors setting is incorrect

    r.handlefunc("/api/task", getalltasks).methods("get", "options")
    r.handlefunc("/api/task", createtask).methods("post", "options")

options Requests will be handled by getalltask​s. In order to allow the content-type header in post requests, the following line should be added to getalltasks:

    w.header().set("access-control-allow-headers", "content-type")

Since createtask does not handle options requests, the following line can be removed:

    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

The above is the detailed content of Issues receiving Axios post data from Reactjs application using Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete