javascript - 为什么 GET 请求被 CORS 策略阻止?
问题描述
我一直在开发一个使用 express 和 cors 的混合应用程序,该应用程序将 get 和 post 请求从客户端 js 文件发送到服务器文件。在使功能正常工作后,我一直在添加收尾工作,并且在发出获取请求时出现以下错误:
从源“http://localhost:8000”访问“http://address:3000/search/Cottonelle”处的 XMLHttpRequest 已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头的值为“ http://address.com' 不等于提供的来源。
“地址”是机器的IP地址。该应用程序允许用户为不同的项目输入条目并将它们发送到服务器进行保存,以及从服务器检索它们。该应用程序在使用'http://localhost'代替地址时工作,通过一些测试我发现它在html的CSP connect-src和客户端js文件中使用的地址都是IP地址时工作,表明问题出在服务器 js 文件上。虽然 get 请求不起作用,但 post 请求仍然有效。post和get请求的区别在于post使用'/post'作为它的路由,而get使用'/search/:query'。以下应该是重现问题的最短必要代码:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com
;connect-src http://address:3000">
<script src="jquery.js"></script>
<script src="client.js"></script>
</head>
<body>
</body>
</html>
客户端.js:
const address = "http://address:3000"
let name = "test"
$.get(address + "/search/" + name ,function(data, status){
alert("The status text is: " + status + "\nThe status code is: " + data);
});
server.js:
const express = require('express')
var cors = require('cors')
const app = express()
var corsOptions = { origin: 'http://address.com', optionsSuccessStatus: 200}
app.use(cors(corsOptions))
const port = 3000
app.get('/search/:query', (req, res) => {
let myStatus = res.statusCode;
res.sendStatus(myStatus)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
解决方案
server.js 授权http://address.com但不是 localhost:8000 (我认为您的网站在本地执行)
要解决您的问题,请在 server.js 的授权主机中添加 localhost:8000
app.use(cors(
{ origin: 'http://address.com', optionsSuccessStatus: 200},
{ origin: 'http://localhost:8000', optionsSuccessStatus: 200}
))