Home > Back-end >  React JS - Getting a CORS error even after require the cors
React JS - Getting a CORS error even after require the cors

Time:11-29

I'm using Express & ReactJS


Express Code:


const Express = require('express');
const PORT = 5000;
const cors = require('cors');

const server = Express();
server.use(cors());   // I've added the cors

server.get('/users', (req, res) => {
    res.send({"users": [ {"user1": "John"}, {"user2": "Nick"} ]);
})


server.listen(PORT, () => {
console.log("server is running on 5000")
});


React Code:


import { useState,useEffect } from 'react';


const Home = () => {

  async function fetchData() {
      try{
        const output = await fetch(`http://localhost:5000/users`);
        console.log(output);
      } catch(e){
          console.error(e);
      }
     
  }

  useEffect(() => {
        fetchData();
     }, [])
  }

    return (
        <h1>FetchData</h1>
    )

 export default Home;


After doing these things... I'm still getting the CORS error in my console.


Here's the full Error Message:

Response { type: "cors", url: "http://localhost:5000/users, redirected: false, status: 500, ok: false, statusText: "Internal Server Error", headers: Headers, body: ReadableStream, bodyUsed: false }

After doing some research, I've found that adding "proxy": "http://localhost:5000" in package.json file will solve the issue. But Nothing is happening.

What should i do now ?

Thanks :)


CodePudding user response:

Try using axios instead of fetch:

// npm install axios

import { useState,useEffect } from 'react';
import axios from 'axios'


const Home = () => {

  async function fetchData() {
      try{
        const output = await axios(`http://localhost:5000/users`);
        console.log(output);
      } catch(e){
          console.error(e);
      }
     
  }

  useEffect(() => {
        fetchData();
     }, [])
  }

    return (
        <h1>FetchData</h1>
    )

 export default Home;

CodePudding user response:

Try with cores options,

const corsOptions = {
  origin: ['http://localhost:<port_of_reactapp>'],
  methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT', 'PATCH'],
};
server.use(cors(corsOptions));

https://expressjs.com/en/resources/middleware/cors.html

CodePudding user response:

If you already npm install cors, in your const server, change const server from const server = Express(); to const server = express();.

https://expressjs.com/en/resources/middleware/cors.html

Or try to use node-http-proxy then just requests from your local host:

http.createServer(function(req, res) {proxy.web(req, res, { target: 'http://localhost:5000/users' });});

Installation: https://github.com/http-party/node-http-proxy

  • Related