【问题标题】:Vue js axios post request to golang server, Preflight errorVue js axios向golang服务器发布请求,预检错误
【发布时间】:2018-02-28 16:31:28
【问题描述】:

我尝试从前端网站 (localhost:8888) 向 golang 后端 (localhost:8000) 发送一个 post api 请求。我收到下面列出的错误。我查看了stackoverflow,问题似乎是跨源请求和预检请求处理。我添加了如下所示的标题,但问题仍然存在。我希望你们能帮助我:)

Axios 错误:

OPTIONS http://localhost:8000/api/heimdall/signup 404 (Not Found)

Failed to load http://localhost:8000/api/heimdall/signup: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 404.

Mux CORS 处理程序

methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
originsOk := handlers.AllowedOrigins([]string{"*"})
headersOk := handlers.AllowedHeaders([]string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"})

log.Fatal(http.ListenAndServe(":8000", handlers.CORS(methodsOk, originsOk, headersOk)(r)))

Axois 代码:

'use strict';

 var axios = require('axios');

function Signup(email, password) {
var apiURL = 'http://localhost:8000/api/heimdall/signup';

return new Promise((resolve, reject) => {
    axios.post(apiURL, {
        email: email,
        password: password
    })
    .then(respone => {
        console.log('Promise Signup response:', respone);
        resolve(respone);
    }, error => {
        console.log('Promise Signup error:', error);
        reject(error);
    });
});
}

export {
   Signup
};

【问题讨论】:

  • 您可以尝试在允许的标题中添加Access-Control-Allow-Origin 吗?看看它是否会起作用

标签: javascript go axios preflight


【解决方案1】:

也许你可以试试这个,我在我的 web api 上使用这个。

var handler http.Handler
{
    handler = handlers.CORS(
        handlers.AllowedOrigins([]string{"*"}),
        handlers.AllowedMethods([]string{"GET", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"}),
        handlers.AllowedHeaders([]string{"Origin", "Authorization", "Content-Type"}),
        handlers.ExposedHeaders([]string{""}),
        handlers.MaxAge(10),
        handlers.AllowCredentials(),
    )(r)
    handler = handlers.RecoveryHandler(handlers.PrintRecoveryStack(true))(handler)
}
http.Handle("/", handler)
http.ListenAndServe(":8080", nil)

【讨论】:

    【解决方案2】:

    我已经在 laravel 5.5 (PHP) 中解决了这类问题

    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Max-Age: 1000");
    header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
    header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
    

    你可以在 golang 上试试这种类型的头文件

    【讨论】:

    • 我尝试了您的两个建议,但它不起作用。预检仍然不成功。
    猜你喜欢
    • 2023-04-03
    • 2017-10-02
    • 2019-04-26
    • 2019-09-29
    • 1970-01-01
    • 2021-01-14
    • 2020-11-19
    • 2021-06-25
    • 2018-08-03
    相关资源
    最近更新 更多