【发布时间】: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);
},
【问题讨论】:
-
错字?
AllowedOrigins: []string{"http://172.0.0.1"}可能是 127.0.0.1 -
一方面,您访问的是 127.0.0.1 的站点,但您将源设置为 172.0.0.1。
-
哦,我的错……我改了,但还是不行。
-
浏览器控制台是否有任何错误信息?此外,您在浏览器中有
http,并执行代码,但在js 代码中有https。 -
http://localhost和http://localhost:8080是不同的来源。实际上,JS 控制台中应该有一条消息。