I'm trying to get information with a fetch (client) and a get (server) requests to get data from the server with the client and printing it. for some reason I can't get the information I'm looking for and I think it has somthing to do with the url I'm entering, can I get an explanation, or maybe an example about the url I'm supposed to enter?
I'll enter my code as an example:
client:
//bitcoin page: url - 'http://localhost:3000/bitcoin'
//NOTE: the proxy is: 'http://localhost:3001'
import React from "react";
import { Link } from "react-router-dom";
function BitCoin() {
const [data, setData] = React.useState(null);
console.log("entered bitcoin page");
React.useEffect(() => {
fetch("NOT SURE WHAT TO WRITE HERE")
.then((res) => res.json())
.then((data) => setData(data.message));
}, []);
return (
<div style={{textAlign:"center", fontFamily:"Comic Sans MC", fontSize:"100"}}>
THIS IS THE BitCoin PAGE
<nav>
<Link to="/"> Home </Link>
</nav>
<nav>
<Link to="/coins"> Coins </Link>
</nav>
<p>{!data ? "Loading..." : data}</p>
</div>
)
}
export default BitCoin;
server:
//index.js: url - 'http://localhost:3001'
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get('NOT SURE WHAT TO WRITE HERE', (req, res) => {
console.log("entered bitcoin query!");
let msg = "";
//some functions to get the msg I'm looking for (not relevant)
res.json({ message: msg });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
as you can see there's a log when entering the get request but the console's not logging it, I'm guessing the client and the server are not communicating and that's what makes the problem.
thank you <3
CodePudding user response:
It's important to understand the general architecture of your technology stack:
You have the React frontend running under
http://localhost:3000
. This is simply serving the React app through a development server on your computer.Additionally, you have a NodeJS app (using express) running at
http://localhost:3001
. Notably, this runs under a different port to the React app.
In your express code, you would define a url which the React frontend can call, to fetch data. So let's call it /coin-message
:
app.get('/coin-message', (req, res) => {
Now, in the React app, you can make ajax requests to this url:
fetch("http://localhost:3001/coin-message")
Note that you need to include the full URL and port in the fetch()
- this is because the Node app runs under a different port.
Important
Because you want to make ajax requests to a URL which has a different port to the React app, you will encounter a Same Origin Policy problem. This is a security measure activated by browsers to prevent web app vulnerabilities. To solve this, you can use one of the CORS middlewares for express, such as this one.
CodePudding user response:
server:
app.get('/bitcoin', ...)
client:
fetch('http://localhost:3001/bitcoin')