I have a Nextjs frontend trying to make a fetch request to my node and express backend but it's not happening for some reason. I'm trying to access this object in the backend: {"data": ["data1", "data2", "data3"]} but I'm not able to even fetch it. Here is my backend code:
const express = require('express')
const app = express()
app.get("/api", (req, res) => {
res.json({"data": ["data1", "data2", "data3"]})
})
app.listen(5000, () => { console.log("Server started on port 5000") })
Here is my next.js file trying to make this request:
import React, { Component, useEffect, useState } from 'react';
const Product = () => {
const [backendData, setBackendData] = useState([{}])
useEffect(() => {
fetch("/api").then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
}, [])
return (
<div>
{(typeof backendData.data === 'undefined') ? (
<p>Loading...</p>
) : (
backendData.data.map((data, i) => (
<p key={i}>{data}</p>
))
)}
</div>
);
}
export default Product
I've included this line in my package.json file "proxy": "http://localhost:5000", so it should be going to that link and when I search http://localhost:5000 in my browser, I get the object that I've written in the backend like this: {"data":["data1","data2","data3"]}.
When I click on Network when I hit inspect on the page, the fetch request doesn't show up either.
Does anyone know why I'm unable to fetch this object in nextjs?