【问题标题】:axios does not send POST to golang apiaxios 不发送 POST 到 golang api
【发布时间】:2017-11-16 18:49:43
【问题描述】:

我有一个带有 negroni 中间件的 golang api 后端。

我已经为 negroni 实现了 CORS 处理程序,所以我的 api 应该允许跨源资源共享。

// allow OPTIONS method of CORS requests
c := cors.New(cors.Options{
    AllowedOrigins: []string{"http://127.0.0.1"},
})

//common.StartUp() - Replaced with init method
// Get the mux router object
router := routers.InitRoutes()
// Create a negroni instance
n := negroni.Classic()
n.Use(c)
n.UseHandler(router)

server := &http.Server{
    Addr:    common.AppConfig.Server,
    Handler: n,
}
log.Println("Listening...")
server.ListenAndServe()

这是来自https://github.com/rs/cors/blob/master/examples/negroni/server.go 使用 negroni 实现 CORS 的示例。

尽管如此,我的 api 现在将 200 状态响应回我的前端,但前端不会将 POST 请求发送到服务器。这是我的 axios 代码:

import axios from 'axios';
const data = {
email: 'user@mail.com',
password: 'secret',
};

export default {
name: 'Login',
methods: {
login() {
  axios.post('https://127.0.0.1:8090/users/login', data);
},

Postman 发送 POST 请求没有任何问题。我做错了什么?

【问题讨论】:

  • 错字? AllowedOrigins: []string{"http://172.0.0.1"} 可能是 127.0.0.1
  • 一方面,您访问的是 127.0.0.1 的站点,但您将源设置为 172.0.0.1。
  • 哦,我的错……我改了,但还是不行。
  • 浏览器控制台是否有任何错误信息?此外,您在浏览器中有http,并执行代码,但在js 代码中有https
  • http://localhosthttp://localhost:8080 是不同的来源。实际上,JS 控制台中应该有一条消息。

标签: go cors axios negroni


【解决方案1】:

好的,我找到了解决问题的方法:

正如this 文章中所述,我为 cors negroni 插件添加了更多选项。我的应用程序中缺少的一个重要选项是

AllowedHeaders: []string{"X-Auth-Key", "X-Auth-Secret", "Content-Type"},

因为我的应用发送了 Content-Type Header 并且 api 拒绝了它。

我希望这能帮助其他有类似问题的人。

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 2022-08-13
    • 1970-01-01
    • 2019-06-20
    • 2018-10-07
    • 2021-08-22
    • 2021-01-17
    • 2020-07-08
    • 2022-01-21
    相关资源
    最近更新 更多