0

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:

when Trying to reach the /add route getting this error.

3
  • 5
    You're not making a POST request. Read what it says, "Cannot GET /add". Commented Mar 18 at 16:15
  • @jonrsharpe — Will you post a formal answer? Commented Mar 18 at 16:17
  • @jonrsharpe I'm trying to add data to database, but it's not working. Just relodging. Can you please let me know. What can I do for that? Commented Mar 18 at 16:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Typing a URL into a browser's address bar will issue a GET request, not a POST request.

You can use some other tool to issue a POST request - e.g., :

curl http://localhost:3000/add -d "country=narinia"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.