NextJS Api Calls

Hi guys, so I am building a simple website with questions and answers and it is in its initial versions. First, I made the backend API using nodejs, express and postgres, watched a tutorial and understood the flow and then added connection pool and so on. My apis are working just fine. I decided to use nextjs for frontend, but I am confused on what is the correct way to make an api call. I watched some tutorials but it still got over my head. Traditional way is to just call the fetch inside the page.tsx where i want to display my data. However, I wanted to use the app/api/route.js method in next js. I assume its called the Internal API. Right now, inside my project folder, I have two folders, client with the nextjs setup and server with nodejs and express api. Now in this scenario, what is the correct way to make the API call from next js while my backend is running on localhost as well. I did read the docs and some stackoverflow questions but I was unable to understand the flow and how I could implement it in my scenario. I am using NextJS Latest version
1 Reply
V3X4TI0US
V3X4TI0USOP7mo ago
const pool = require('./connection.js')
const express = require('express');
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");

app.use(express.json());
app.use(
cors({
origin: "http://localhost:5173",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);

app.use(bodyParser.json());


// Route handler for the root URL
app.get('/', (req, res) => {
res.send('Welcome to the Q&A API');
});


// GET ALL QUESTIONS
app.get("/questions", async (req, res) => {
const selectQuery = `
SELECT * FROM questions q INNER JOIN answers a
ON q.question_id = a.question_id
`;

try {
const { rows } = await pool.query(selectQuery);
res.json({ rows });
const questions = rows
console.log(questions[0])
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
const pool = require('./connection.js')
const express = require('express');
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");

app.use(express.json());
app.use(
cors({
origin: "http://localhost:5173",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);

app.use(bodyParser.json());


// Route handler for the root URL
app.get('/', (req, res) => {
res.send('Welcome to the Q&A API');
});


// GET ALL QUESTIONS
app.get("/questions", async (req, res) => {
const selectQuery = `
SELECT * FROM questions q INNER JOIN answers a
ON q.question_id = a.question_id
`;

try {
const { rows } = await pool.query(selectQuery);
res.json({ rows });
const questions = rows
console.log(questions[0])
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
Here is a basic route inside my api.js file which inside my server folder Backend is working just fine
Want results from more Discord servers?
Add your server