Xmlhttprequest failing due to No 'Access-Control-Allow-Origin' [React/Mongo/Axios]

Asked

Viewed 2,001 times

0

I have a backend running on localhost with the following code:

server.js:

const port = 3003
const bodyParser = require('body-parser')
const express = require('express')
const server = express()
const allowCors = require('./cors')

server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
server.use(allowCors)

server.listen(port, function() {
    console.log(`BACKEND rodando na porta ${port}.`)
})

module.exports = server

Cors.js:

module.exports = function(req, res, next) {
    res.header("Acess-Control-Allow-Origin", "*")
    res.header('Acess-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    res.header('Acess-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
    next()
}

When I make a request via Postman, everything happens well and works, I can use POST and GET, but in frontend, when I make a request via Xios, I get returned this error:

Error:

Erro

Request:

Axios.post('http://localhost:3003/api/todos', {description}).then(resp => console.log('Funcionou!'))

More code from the backend:

Routes.js:

const express = require('express')

module.exports = function(server) {

    //API Routes
    const router = express.Router()
    server.use('/api', router)

    //TODO Routes
    const todoService = require('../api/todo/todoService')
    todoService.register(router, '/todos')
}

todoService.js:

const Todo = require('./todo')

Todo.methods(['get', 'post', 'put', 'delete'])
Todo.updateOptions({new: true, runValidators: true})

module.exports = Todo

Everything makes me believe that I made some way wrong the configuration of CORS, but I’ve tried everything and I can’t get it right

1 answer

1

You need to add a library to your Express call CORS. It abstracts this part of the request and enables cross origin.

To use is very simple:

const port = 3003
const bodyParser = require('body-parser')
const cors = require('cors')
const express = require('express')
const server = express()

server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
server.use(cors())


server.listen(port, function() {
    console.log(`BACKEND rodando na porta ${port}.`)
})

module.exports = server

Browser other questions tagged

You are not signed in. Login or sign up in order to post.