Search code examples
corsjson-server

no cors config not working with json-server


I'm using json-server to create a mock API of my actual API for offline testing purpose. I can see the mock API response under their Url endpoint: localhost:5001/api/searchresults/*

but on my app I cannot see the results because the request is blocked by CORS. Reading the json-server docu, there is a way to disable CORS issues, adding jsonServer.defaults({ noCors: true }) as middleware.

I than add a custom server and run this with node server.js

// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults({ noCors: true })

server.use(middlewares)

server.use('/api/searchresults', router)
server.listen(5001, () => {
  console.log('Mock api server listening at localhost:5001')
})

but unfortunately I still get cors issues when try to fetch my data.

Anyone has an idea why is not working or how to address this problem?

Here is the full project: https://github.com/ElliotForWater/efw-webapp


Solution

  • Since it seems that the json-server package is not mantained anymore https://github.com/typicode/json-server/issues/1219 I figured out a way to fix it with just Express

    server.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
      res.header('Access-Control-Allow-Headers', '*')
      next()
    })
    

    Adding those lines worked for us I hope can be helpful for someone else in similar situation