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

Issues receiving Axios post data from Reactjs application using Golang

王林
Release: 2024-02-06 08:39:08
forward
563 people have browsed it

使用 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);
            });
        }
    };
Copy after login

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)
}
Copy after login

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"`
}
Copy after login

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")
Copy after login

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)
Copy after login

Conflicts with:

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

The title should be replaced with:

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

2. cors setting is incorrect

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

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")
Copy after login

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")
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template