英文:
Error: CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource SvelteKit
问题
我有2个文件夹,一个叫做"backEnd",另一个是"frontEnd"
结构:
|-backEnd
|--app.js
|-frontEnd
|--src
|---routes
|---- +page.svelte
|---- +page.js
在backEnd中,我使用了Node.js和Express,以下是代码:
let express = require("express")
let app = express()
let PORT = process.env.PORT || 3000
app.get("/api", (req, res) => {
res.json({message: "Hello World"})
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
在frontEnd中,我使用了SvelteKit和Vite,以下是"+page.js"中的代码:
export let load = async ({ fetch }) => {
let rawRes = await fetch("http://localhost:3000/api/")
let data = await rawRes.json()
return {data: data}
}
以及"page.svelte"中的代码:
<script>
export let data
console.log(data)
</script>
<div>
Hello
</div>
当我运行"npm run dev"时,我收到以下错误信息:"Error: CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource"。
如何修复这个问题?
英文:
I have 2 folder, one called "backEnd" and another is "frontEnd"
structure:
|-backEnd
|--app.js
|-frontEnd
|--src
|---routes
|---- +page.svelte
|---- +page.js
backEnd I use nodejs with express, here is the code
let express = require("express")
let app = express()
let PORT = process.env.PORT || 3000
app.get("/api", (req, res) => {
res.json({message: "Hello World"})
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
The frontEnd I use sveltekit with vite
Here is the code in "+page.js"
export let load = async ({ fetch }) => {
let rawRes = await fetch("http://localhost:3000/api/")
let data = await rawRes.json()
return {data: data}
}
And here is the code in "page.svelte"
<script>
export let data
console.log(data)
</script>
<div>
Hello
</div>
When I run "npm run dev" I get the error
"Error: CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource"
How can I fix this
答案1
得分: 0
例如:
let express = require("express")
let cors = require('cors')
let app = express()
let PORT = process.env.PORT || 3000
app.use(cors())
app.get("/api", (req, res) => {
res.json({message: "Hello World"})
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
英文:
Use cors middleware to enable CORS for the server.
E.g.
let express = require("express")
let cors = require('cors')
let app = express()
let PORT = process.env.PORT || 3000
app.use(cors())
app.get("/api", (req, res) => {
res.json({message: "Hello World"})
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论