发送GET请求到您机器上的数据库的URL是什么?



我使用ajax发送GET请求从我的机器上的数据库检索信息,目前它给了我以下错误:

'从'http://127.0.0.1:5501'访问'http://localhost:3000/api/groceries'的XMLHttpRequest已被CORS策略阻止:所请求的资源上没有'Access- control - allow - origin '标头'。'

这是我在App组件中为GET请求发送的ajax请求:

getGroceries () {
$.ajax({
method: 'GET',
url: 'http://localhost:3000/api/groceries',
success: (groceries) => this.setState({
groceries: groceries
}),
error: error => console.log(error)
})
}

这是我在我的机器上设置的服务器:

const express = require('express')
const app = express()
const port = 3000
const groceryController = require('./Controller/controllerGrocery.js')
app.get('/api/grocery', (req, res) => {
groceryController.getGrocery(req, res)
})
app.use(express.urlencoded({extended: true}));
app.post('/api/grocery', (req, res) => {
groceryController.addGrocery(req, res)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})

在ajax中检索GET请求信息的正确URL是什么?谢谢!

URL可能没有问题,但是CORS有问题。

您需要启用CORS (Cross-Origin Resource Sharing)。

你可以在这里找到更多关于CORS的信息:=介绍,https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny: ~:文本域% 20比% 20 % 20源% 20域。

你需要做的是在你的服务器上启用CORS。

在项目中添加cors包:

npm install cors或纱线添加cors

并在server.js(或主后端.js文件)上使用:

const cors = require("cors");
app.use(cors());

最新更新