How can I enter an input in my App.js file and retrieve is in the go backend server using the FormValue() function? I don't want to send the values as a JSON object. The endpoint the form should post to is the PostForm function in Server.go.
The go server should be able to serve the bundled react files without separately sending the input in react to a separate go server and then getting the information back.
Errors: Currently, when I enter something into the input form, the browser goes to "Cannot POST /api/postform"
Thanks!
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>React Starter</title>
</head>
<body>
<div id="root"></div>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<script src="../dist/bundle.js"></script> <!--references the react app -->
</body>
</html>
app.js
import React, { Component} from "react";
class App extends Component{
constructor() {
super();
this.state = {
query: '',
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
query: event.target.value
});
}
render() {
return(
<div className="App">
<h1> Hello, World! </h1>
<form action="/api/postform" method="POST">
<input type="text" name="query" onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["@babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
server.go
package main
import (
"net/http"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
"fmt"
)
func main() {
// Set the router as the default one shipped with Gin
router := gin.Default()
router.Use(static.Serve("/", static.LocalFile("./index.html", true)))
// Setup route group for the API
api := router.Group("/api")
{
api.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H {
"message": "pong",
})
})
}
// input form should hit this function when it posts
api.POST("/postform", PostForm)
router.Run(":5000")
}
// should be able to retrieve the value netered into the form and print it out.
func PostForm(c *gin.Context) {
c.Header("Content-Type", "application/json")
q := c.Request.FormValue("query")
fmt.Println("VALUE IS: ", q)
}