Here is the code for the index.js
of my expressjs project. I'm new to Node.js and trying to understand how to develop a web app using MERN Stack.
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const app = express();
const port = 3000;
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "12345678",
port: 5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
async function checkVisisted() {
const result = await db.query("SELECT country_code FROM visited_countries");
let countries = [];
result.rows.forEach((country) => {
countries.push(country.country_code);
});
return countries;
}
// GET home page
app.get("/", async (req, res) => {
const countries = await checkVisisted();
res.render("index.ejs", { countries: countries, total: countries.length });
});
//INSERT new country
app.post("/add", async (req, res) => {
const input = req.body["country"];
const result = await db.query(
"SELECT country_code FROM countries WHERE country_name = $1",
[input]
);
if (result.rows.length !== 0) {
const data = result.rows[0];
const countryCode = data.country_code;
const final_data = await db.query("INSERT INTO visited_countries (country_code) VALUES ($1)", [
countryCode,
]);
res.redirect("/");
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});`
When trying to reach http://localhost:3000/add route, I get this error:
I think that the problem is in the way you structure your post route and in which context are you using it..
You can't just type "/add" in your browser address bar. That's a GET request, but your code only handles POST.
You need to add in your index.ejs file a form like this:
<form action="/add" method="POST">
<input type="text" name="country" placeholder="Enter a country">
<button type="submit">Add Country</button>
</form>
Just put this form on your page, fill a country name, and submit. That will trigger the POST request your route is expecting. Browser address bars can only do GET requests.
@Extra: If you want to test your POST route directly without creating a form, Insomnia is perfect for that. Just download Insomnia, create a new POST request to http://localhost:3000/add, set the body to 'Form URL Encoded' format, add a key-value pair with 'country' as the key and your country name as the value, then hit send. It's way easier for testing API endpoints than trying to build forms every time. You can test routes almost in real-time, that will boost your production.