reactjs - axios.post请求获取404

标签 reactjs go axios go-gin

客户端(React/axios.post)无法通过状态代码404发布到服务器端api(Golang/gin)。
我想使此帖子请求成功。

在curl成功之后将数据写入mysql表

curl -X POST -H "Content-Type: application/json" -d '{"title":"bbb", "content":"bbb"}' localhost:4000/api/post

但是,如果是axios.post,则会发生404错误。

这是目标源代码。
interface ArticleState {
  title: string;
  content: string;
  redirect: boolean;
}

class Post extends React.Component<{}, ArticleState> {
  constructor(props: {}) {
    super(props);
    this.state = {
      title: '',
      content: '',
      redirect: false,
    };

    this.handleChangeTitle = this.handleChangeTitle.bind(this);
    this.handleChangeContent = this.handleChangeContent.bind(this);
    this.setRedirect = this.setRedirect.bind(this);
    this.renderRedirect = this.renderRedirect.bind(this);
  }

  handleChangeTitle(e: React.FormEvent<HTMLInputElement>) {
    this.setState({title: e.currentTarget.value});
  }

  handleChangeContent(e: React.FormEvent<HTMLInputElement>) {
    this.setState({content: e.currentTarget.value});
  }

  setRedirect() {
    this.setState({
      redirect: true,
    });

    const data = {title: this.state.title, content: this.state.content};
    axios.post('http://localhost:4000/api/post', data).then(res => {
      console.log(res);
    });
  }

  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to="/post/finish" />;
    }
  };

  render() {
    return (
      <Container text style={{marginTop: '3em'}}>
        <Form onSubmit={this.setRedirect}>
          <Form.Input
            label="Title"
            name="title"
            value={this.state.title}
            onChange={this.handleChangeTitle}
          />
          <Form.Field
            label="Content"
            name="content"
            value={this.state.content}
            control="textarea"
            onChange={this.handleChangeContent}
          />
          {this.renderRedirect()}
          <Form.Button content="Submit" />
        </Form>
      </Container>
    );
  }
}
type Article struct {
    ID      int    `json:"id"`
    TITLE   string `json:"title"`
    CONTENT string `json:"content"`
}

var articles []Article

func main() {

    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/article")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    router := gin.Default()

    api := router.Group("/api")
    {
        api.POST("/post", func(c *gin.Context) {
            var article Article
            c.BindJSON(&article)
            c.Header("Content-Type", "application/json")
            c.Header("Access-Control-Allow-Origin", "*")
            ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")
            if err != nil {
                log.Fatal(err)
            }
            ins.Exec(article.TITLE, article.CONTENT)
            c.JSON(http.StatusOK, gin.H{"status": "ok"})
        })
    }
    router.Run(":4000")
}


我希望axios.post成功请求,但实际上失败并显示404状态。
OPTIONS http://localhost:4000/api/post 404 (Not Found)
Access to XMLHttpRequest at 'http://localhost:4000/api/post' 
from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource.
createError.js:17 Uncaught (in promise) Error: Network Error
    at createError (createError.js:17)
    at XMLHttpRequest.handleError (xhr.js:80)

最佳答案

这是我测试过的工作代码:

type Article struct {
    ID      int    `json:"id"`
    TITLE   string `json:"title"`
    CONTENT string `json:"content"`
}

var articles []Article

func main() {

    db, err := sql.Open("mysql", "root:111111@tcp(localhost:3306)/article")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    router := gin.Default()

    router.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"*"},
        AllowMethods:     []string{"GET", "POST", "OPTIONS"},
        AllowHeaders:     []string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        AllowOriginFunc: func(origin string) bool {
            return true
        },
        MaxAge: 15 * time.Second,
    }))
    api := router.Group("/api")
    {

        api.POST("/post", func(c *gin.Context) {
            var article Article
            c.BindJSON(&article)
            ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")
            if err != nil {
                log.Fatal(err)
            }
            ins.Exec(article.TITLE, article.CONTENT)
            c.JSON(http.StatusOK, gin.H{"status": "ok"})
        })
    }
    router.Run(":4000")
}

关于reactjs - axios.post请求获取404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976754/

相关文章:

javascript - 如何修复 React Context 的对象不是函数 - TypeError

regex - 使用正则表达式按值同时读取两个文件

go - 拉取单个go标准包的副本进行修改

reactjs - 如何将 axios 中的数组参数传递到 Spring Controller ?

javascript - react axios 401未经授权

javascript - 如何读取axios中获取的链接的txt文件?

javascript - React 组件条件渲染后重置状态

javascript - 如何将对象中的股票数据解析为数组

html - Svg defs 封装

pointers - Go:是否可以返回指向函数的指针