【问题标题】:How Can I Link back end Go server to front end ReactJS?如何将后端 Go 服务器链接到前端 ReactJS?
【发布时间】:2019-05-10 19:57:27
【问题描述】:

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

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

错误: 目前,当我在输入表单中输入内容时,浏览器会转到“Cannot POST /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)

}

【问题讨论】:

  • 当前代码有什么问题?你有任何错误吗?如果是这样,可以将它们包括在问题中。
  • 感谢您回复我。当我在输入中输入内容时,浏览器会输出“Cannot POST /api/postform”
  • 我在这里可能错了,但在我看来,从 webpack 配置和 server.go 文件来看,您正在运行两个相互通信的服务器。您正在使用正在侦听端口 :3000 的服务器为 react 应用程序提供服务,并且您正在为正在侦听端口 :5000 的服务器上提供 go api。当您从localhost:3000/api/postform 发出请求时,该请求将被发送到localhost:3000/api/postform,而不是您可能认为的localhost:5000/api/postform
  • 您要么必须从同一台服务器同时提供 api 和 react 应用程序,要么将请求从一台服务器显式发送到另一台服务器,例如尝试更新表单的操作像这样&lt;form action="http://localhost:5000/api/postform" method="POST"&gt;

标签: reactjs forms go server


【解决方案1】:

一般前端 App 使用 Restful API 连接到服务器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2021-11-28
    • 2021-09-14
    • 2016-07-12
    相关资源
    最近更新 更多