go - axios 不发送 POST 到 golang api

标签 go cors axios negroni

我有一个带有 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: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d484e584f7d505c5451135e5250" rel="noreferrer noopener nofollow">[email protected]</a>',
password: 'secret',
};

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

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

最佳答案

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

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

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

因为我的应用程序发送了 Content-Type header ,但 api 拒绝了它。

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

关于go - axios 不发送 POST 到 golang api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309286/

相关文章:

javascript - 在 Express 中设置默认响应 header

javascript - NodeJS - FormData 向服务器发送未定义的值

go - 你好.go :1:1: illegal character U+0023

java - Tomcat Jersey 在 "OPTIONS"飞行前请求上阻止服务器

go - 下载并安装Visual Studio Code Go依赖项

asp.net-core - Blazor oauth2 被 CORS 阻止

node.js - Kubernetes 上的 Node.js 容器中的 Axios 返回 "ECONNREFUSED 127.0.0.1:30561"?

typescript - 我应该如何测试 React Hook "useEffect"使用 Typescript 进行 api 调用?

dll - 是否可以在平板电脑上运行我的 Windows 8 C/go/html 程序

go - 如何在 Golang 中设置 GODEBUG 环境变量,以便我可以将 godebug 与 net/http 一起使用