如何将后端Go服务器链接到前端ReactJS?

时间:2019-05-10 19:57:28

标签: reactjs forms go server

如何在我的App.js文件中输入输入并使用FormValue()函数在go后端服务器中进行检索?我不想将值作为JSON对象发送。表单应发布到的端点是Server.go中的PostForm函数。

go服务器应该能够提供捆绑的react文件,而无需将输入中的输入单独发送给单独的go服务器,然后将信息取回。

错误: 目前,当我在输入表单中输入内容时,浏览器转到“无法发布/ api / postform”

谢谢!

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)

}

1 个答案:

答案 0 :(得分:0)

通常,前端应用程序通过Restful API连接到服务器。