猿问

axios.post 请求得到 404

客户端(React/axios.post)无法发布到服务器端 api(Golang/gin),状态代码为 404。我想让这个发布请求成功。


如下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>

    );

  }

}


明月笑刀无情
浏览 243回答 3
3回答

神不在的星期二

这是我测试过的工作代码:type Article struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; int&nbsp; &nbsp; `json:"id"`&nbsp; &nbsp; TITLE&nbsp; &nbsp;string `json:"title"`&nbsp; &nbsp; CONTENT string `json:"content"`}var articles []Articlefunc main() {&nbsp; &nbsp; db, err := sql.Open("mysql", "root:111111@tcp(localhost:3306)/article")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err.Error())&nbsp; &nbsp; }&nbsp; &nbsp; defer db.Close()&nbsp; &nbsp; router := gin.Default()&nbsp; &nbsp; router.Use(cors.New(cors.Config{&nbsp; &nbsp; &nbsp; &nbsp; AllowOrigins:&nbsp; &nbsp; &nbsp;[]string{"*"},&nbsp; &nbsp; &nbsp; &nbsp; AllowMethods:&nbsp; &nbsp; &nbsp;[]string{"GET", "POST", "OPTIONS"},&nbsp; &nbsp; &nbsp; &nbsp; AllowHeaders:&nbsp; &nbsp; &nbsp;[]string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With"},&nbsp; &nbsp; &nbsp; &nbsp; ExposeHeaders:&nbsp; &nbsp; []string{"Content-Length"},&nbsp; &nbsp; &nbsp; &nbsp; AllowCredentials: true,&nbsp; &nbsp; &nbsp; &nbsp; AllowOriginFunc: func(origin string) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; MaxAge: 15 * time.Second,&nbsp; &nbsp; }))&nbsp; &nbsp; api := router.Group("/api")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; api.POST("/post", func(c *gin.Context) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var article Article&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.BindJSON(&article)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ins.Exec(article.TITLE, article.CONTENT)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.JSON(http.StatusOK, gin.H{"status": "ok"})&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; router.Run(":4000")}

慕码人8056858

正如错误所示,请求“已被 CORS 策略阻止”,CORS 策略是“跨域资源共享”的缩写,是浏览器实施的一项安全措施。解决方案是修改您的服务器以返回正确的“Access-Control-Allow-Origin”标头。

翻阅古今

在服务器端添加一些代码后,问题得到解决。&nbsp; &nbsp; &nbsp; &nbsp; api.POST("/post", func(c *gin.Context) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Content-Type", "application/json")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Access-Control-Allow-Origin", "*")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // add&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Access-Control-Allow-Headers", "Content-Type")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var article Article&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.BindJSON(&article)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ins, err := db.Prepare("INSERT INTO articles(title,content) VALUES(?,?)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ins.Exec(article.TITLE, article.CONTENT)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.JSON(http.StatusOK, gin.H{"status": "ok"})&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; // add response to OPTIONS&nbsp; &nbsp; &nbsp; &nbsp; api.OPTIONS("/post", func(c *gin.Context) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Content-Type", "application/json")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Access-Control-Allow-Origin", "*")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Access-Control-Allow-Headers", "Content-Type")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.JSON(http.StatusOK, gin.H{"status": "ok"})&nbsp; &nbsp; &nbsp; &nbsp; })
随时随地看视频慕课网APP

相关分类

Go
我要回答