最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - post route is not working in my express js project - Stack Overflow

programmeradmin3浏览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:

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:

Share Improve this question edited Mar 18 at 16:39 Mureinik 313k54 gold badges362 silver badges392 bronze badges asked Mar 18 at 16:13 H HasanH Hasan 631 silver badge8 bronze badges 3
  • 5 You're not making a POST request. Read what it says, "Cannot GET /add". – jonrsharpe Commented Mar 18 at 16:15
  • @jonrsharpe — Will you post a formal answer? – Sergey A Kryukov 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? – H Hasan Commented Mar 18 at 16:20
Add a comment  | 

2 Answers 2

Reset to default 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.

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:

curl http://localhost:3000/add -d "country=narinia"
发布评论

评论列表(0)

  1. 暂无评论