简体   繁体   English

axios不会将POST发送到golang api

[英]axios does not send POST to golang api

I have a golang api backend with a negroni middleware. 我有一个带有negroni中间件的golang api后端。

I already implemented the CORS handler for negroni, so my api should allow cross origin resource sharing. 我已经为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()

This is from the https://github.com/rs/cors/blob/master/examples/negroni/server.go example of implementing CORS with negroni. 这来自使用negroni实现CORS的https://github.com/rs/cors/blob/master/examples/negroni/server.go示例。

Nevertheless my api now responses a 200 status back to my frontend, but the frontend does not send the POST request to the server. 尽管如此,我的api现在会向前端响应200状态,但是前端不会将POST请求发送到服务器。 This my axios code: 这是我的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 does not have any problems with sending the POST request. Postman在发送POST请求方面没有任何问题。 What am I doing wrong? 我究竟做错了什么?

Okay I found a solution for the problem: 好的,我找到了解决该问题的方法:

As described in this article, I added some more options to the cors negroni plugin. 正如在描述这个文章,我增加了一些更多的选择到CORS内格罗尼插件。 One important option that was missing in my application was the line 该行中缺少的一个重要选项是

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

Because my app sent the Content-Type Header and the api refused it. 因为我的应用发送了Content-Type标头,但api拒绝了它。

I hope this will help others with similar problems. 我希望这会对其他有类似问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM