I am trying to run React application using JSON server- as my backend API. But getting CORS error while running on different port
I need some solution so that i can run on same port Thanks in Advance!
You can't open the same port twice.
You have basically two options
You can integrate proxy directly using nodejs - CRA supports this option: https://create-react-app.dev/docs/proxying-api-requests-in-development/
Conveniently, this avoids CORS issues and error messages like this in development:
Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Implement CORS headers is not as hard as it might look like.
Please see the documentation of the json server: https://www.npmjs.com/package/json-server
const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)
There is also a CLI option if you use json-server directly via command line. By default, CORS are enabled. Therefore it seems that you need the jsonServer.defaults() to create your middlewares.