Home > OS >  How can I get URL from node.js to react.js?
How can I get URL from node.js to react.js?

Time:09-27

Currently, Im trying to fetch data from node.js to react.js. And I'm using useEffect to get the data from node.js but for some reason, i can not get the URL from node js. I'm really new to node.js with react.js So I want to know what is a proper way to fetch the data . This is my code :

Server

const app = express();

var client_id =
  "???????????????????????????????????????";
var client_secret =
  "???????????????????????????????????????";
var state_val = "RANDOM_STATE";
var redirectURI = "http://localhost:5000/callback";


app.get("/", function (req, res) {
  let api_url =
    "https://www.?????.co.kr/oauth2.0/authorize?response_type=code&client_id="  
    client_id  
    "&redirect_uri="  
    redirectURI  
    "&state="  
    state_val;
  res.send("<a href='"   api_url   "'>로그인</a>");
});

Client

  const [d, setd] = useState();
  useEffect(() => {
    fetch("http://localhost:5000/")
      .then(res => {
        return res.send();
      })
      .then(data => {
        console.log(data);
        setd(data);
      });
  }, []);
  console.log(d);

And when i access this, i got error like this: enter image description here

but when i change the fetch Url like "http://localhost:5000/callback" then it doesn't get the error

CodePudding user response:

You are making a cross origin fetch request and so your server needs to respond with the correct Access-Control-* headers. In this case you need Access-Control-Allow-Origin.

You can use the cors package.

import cors from 'cors'

const app = express();

var client_id =
  "???????????????????????????????????????";
var client_secret =
  "???????????????????????????????????????";
var state_val = "RANDOM_STATE";
var redirectURI = "http://localhost:5000/callback";

app.use(cors())

app.get("/", function (req, res) {
  let api_url =
    "https://www.?????.co.kr/oauth2.0/authorize?response_type=code&client_id="  
    client_id  
    "&redirect_uri="  
    redirectURI  
    "&state="  
    state_val;
  res.send("<a href='"   api_url   "'>로그인</a>");
});

CodePudding user response:

If you have set everything right, it seems related to the CORS problem. try adding the below middleware to your code:

// Add headers before the routes are defined
app.use(function (req, res, next) {

    // this is related to websites you want to allow them to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // you can limit the API methods accordingly
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // choose the headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');


    // Pass to next level
    next();
});

CodePudding user response:

Just curious to know is there any specific reason why you are running node js and react js in separate ports.

  • Related