'How do I make an API request from client (Ion + React) to server (NodeJS)? Proxy is not working
So I have an application built with Ionic and React and a backend built with NodeJS. Right now I am trying to make an HTTP fetch request from client to server. The client is running on Ionic's 8100 PORT whereas my NodeJS server is running on 3001. I tried adding the following to my package.json in my client side code
{
"name": "______",
"version": "0.0.1",
"private": true,
"proxy": "http://localhost:3001",
}
But I am getting this error: Proxy error: Could not proxy request /api/test from localhost:8100 to http://localhost:3001.
My simple route is below
const router = require("express").Router();
// Use Router to modularize routes, instead of combing
// with the main app.
router.get("/test", (req, res) => {
console.log("MADE IT IN HERE")
res.json("Hello World");
})
module.exports = router;
And the rest of my server code
const express = require("express");
const apiRoutes = require("./routes/apiRoutes");
const cors = require("cors");
const sequelize = require("./config/connection");
// Initializing the app and creating a port.
const app = express();
app.use(cors());
const PORT = process.env.PORT || 3001;
// Body parsing and route middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/api', apiRoutes);
// Start the server on the port
sequelize.sync({force:false}).then(() => {
app.listen(PORT, () => console.log(`Listening on PORT: ${PORT}`));
})
And lastly, how I am calling that API endpoint from the client side in React
const FindChallenges: React.FC = () => {
const { isAuthenticated } = useAuth0();
const [searchedChallenge, setSearchedChallenge] = useState<string>(); // what user searched.
const [challenges, setChallenges] = useState<string>(); // the challenges that match search.
const getAllChallenges = () => {
console.log("GETTING ALL CHALLENGES NOW")
fetch("/api/test", {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(data => data.json())
.then(res => console.log(res))
}
Any suggestions? Thanks!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
