【发布时间】:2021-10-24 15:50:44
【问题描述】:
我正在使用 ajax 发送 GET 请求以从我机器上的数据库中检索信息,目前它给了我以下错误:
'从源'http://127.0.0.1:5501' 访问'http://localhost:3000/api/groceries' 的 XMLHttpRequest 已被 CORS 策略阻止:否'Access-Control-Allow-Origin '请求的资源上存在标头。'
这是我为应用组件中的 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 是什么?谢谢!
【问题讨论】: