douzhajie7168 2019-07-10 18:35
浏览 1071
已采纳

axios.post请求获取404

Client side(React/axios.post) failed to post to server side api (Golang/gin) with status code 404. I want to make this post request success.

Following curl success to write data in mysql table

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

But, in case of axios.post, 404 error occurs.

This is target source code.

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")
}

I expect axios.post success to request, but actually failed with 404 status.

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)
  • 写回答

3条回答 默认 最新

  • dongmiao520892 2019-07-10 19:52
    关注

    Here is the working code that I tested:

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮