2

我有一个带有 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 请求没有任何问题。我究竟做错了什么?

4

1 回答 1

4

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

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

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

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

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

于 2017-11-16T10:49:43.587 回答