为了账号安全,请及时绑定邮箱和手机立即绑定

axios.post 请求得到 404

axios.post 请求得到 404

Go
明月笑刀无情 2023-07-04 10:00:32
客户端(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>    );  }}
查看完整描述

3 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

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


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

}


查看完整回答
反对 回复 2023-07-04
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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



查看完整回答
反对 回复 2023-07-04
?
翻阅古今

TA贡献1780条经验 获得超5个赞

在服务器端添加一些代码后,问题得到解决。


        api.POST("/post", func(c *gin.Context) {

            c.Header("Content-Type", "application/json")

            c.Header("Access-Control-Allow-Origin", "*")

            // add 

            c.Header("Access-Control-Allow-Headers", "Content-Type")

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

        })

        // add response to OPTIONS

        api.OPTIONS("/post", func(c *gin.Context) {

            c.Header("Content-Type", "application/json")

            c.Header("Access-Control-Allow-Origin", "*")

            c.Header("Access-Control-Allow-Headers", "Content-Type")

            c.JSON(http.StatusOK, gin.H{"status": "ok"})

        })


查看完整回答
反对 回复 2023-07-04
  • 3 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信