我有一个带有 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);
},
最佳答案
好的,我找到了问题的解决方案:
如 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/