dqd78456 2019-05-10 19:57
浏览 142

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

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)

}
  • 写回答

1条回答 默认 最新

  • douyanjing8287 2019-05-10 23:22
    关注

    Generally Front end App Connect to Server with Restful API.

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试