gpt4 book ai didi

javascript - 从 http ://localhost:8080 请求时不允许 Apache 服务器方法

转载 作者:行者123 更新时间:2023-12-01 02:28:13 27 4
gpt4 key购买 nike

我无法理解我的代码是否格式错误或者我在 apache 服务器上配置了错误。我正在 VueJs2 中开发应用程序,该应用程序正在 http://localhost:8080 (通过 npm run dev)上运行,并且我正在我的 Apache2 服务器(MAMP)上发出请求,该服务器在 myapp 上有虚拟主机。测试。我已经启用了我知道的所有访问控制选项,但是当我在 get 请求中设置 header (在 js 代码中)时,开发人员工具显示此请求方法是 OPTIONS 并且我未获得授权。如果我删除 JS 代码中的 header ,请求响应为 200 OK(方法 GET)。

这是我来自 vuejs2 的 js 代码

this.$http.get(this.$apiUrl + `rest/api/public/User/user/` + payload.id_user, {
// if i remove this headers, request works OK
headers: {
'Content-Type': 'application/json',
'JwtToken': token
}
})

这是我的 apache 虚拟主机配置

<VirtualHost *:80>
ServerName spotscouting.test
ServerAlias *.spotscouting.test
ServerAdmin info@spotscouting.test
DocumentRoot "/Users/davorpecnik/workspace/spot-scouting-adminpage"
LogLevel debug
ErrorLog "/Users/davorpecnik/workspace/spot-scouting-adminpage/rest/application/logs/spotscouting.test-error_log"
CustomLog "/Users/davorpecnik/workspace/spot-scouting-adminpage/rest/application/logs/spotscouting.test-access_log" common
<Directory "/Users/davorpecnik/workspace/spot-scouting-adminpage">
Options Indexes FollowSymLinks
AllowOverride All
Allow from all
</Directory>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Max-Age "1000"
</VirtualHost>

开发者工具中的网络 enter image description here

你能告诉我出了什么问题吗?如果您需要任何其他信息,请告诉我,我会提供。谢谢

最佳答案

OPTIONS 是进行 http 调用时发送的飞行前请求。

here 中所述

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

在您的 Apache 虚拟主机中,添加选项

Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"

您还需要设置适当的 header 才能成功发出请求。对于 JWT Token,您可以通过 Authorization header 发送。

this.$http.get(this.$apiUrl + `rest/api/public/User/user/` + payload.id_user, {
// if i remove this headers, request works OK
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
})

关于javascript - 从 http ://localhost:8080 请求时不允许 Apache 服务器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com