简体   繁体   中英

Cross-Origin Request Cors in NodeJS

I want to fetch my NodeJS server, but I receive a Cross-Origin Request echec.

This is my index.js server:

const express = require('express')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()

const routerIdeas = require('./routes/ideas')

const PORT = process.env.PORT || 5000
const app = express()

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    res.send(200)
    next()
})

app.use('/api', routerIdeas)

app.listen(PORT, () => {
    console.log(`Server is running on port : ${PORT}`)
})

I also tried with the npm CORS package but it's the same problem:

const express = require('express')
var cors = require('cors')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()

const routerIdeas = require('./routes/ideas')

const PORT = process.env.PORT || 5000
const app = express()

app.use(cors())

app.use('/api', routerIdeas)

app.listen(PORT, () => {
    console.log(`Server is running on port : ${PORT}`)
})

And this is my fetch by the React app:

useEffect(() => {
        const getIdeas = async () => {
            setIsLoading(true)
            try {
                const response = await fetch("https://localhost:3004/api/ideas")
                const data = await response.json()
                setIdeasArray(data)
                setIsLoading(false)
            } catch (err) {
                console.error('getIdeas error: ', err, err.stack)
            }
        }
        getIdeas()
    }, [])

The browser's console always answer: Blocking a Cross-Origin Request: the "Same Origin" policy does not allow viewing of the remote resource located at https://localhost:3004/api/ideas. Reason: CORS request failed.

Sorry, it was just a stupid error:

Wrong fetch URL => https://localhost:3004/api/ideas

Good fetch URL => http://localhost:3004/api/ideas

Why don't you use CORS node package ( link )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM