首页 > 解决方案 > Cannot Get in Node Js

问题描述

I am new to node js and creating a simple application to query data stored in database(MySql) .So what i am doing is, I have created a database named stock and i am querying it using index.html to show it at get.html but after executing the get request i am not able to get the result. Here is my app.js

const express=require('express');
const app=express();
const port= 5050;
const bodyParser=require("body-parser");

app.use(bodyParser.urlencoded({extended:false}));

app.get('/',(req,res)=>res.sendFile(__dirname + '/index.html'));

app.post('/get',function(req,res){
const mysql=require('mysql');


const con=mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"abc123",
    database:"abc",
});

con.connect(function(err){
    if(err) throw err;
    console.log("Connected");
    let sqlQuery='SELECT * FROM stock';
con.query(sqlQuery,(err,rows)=>{
    if(err) throw err;
    console.log('Data Received:-');
    console.log(rows);


        });
    });
});
app.listen(port);

My Index.html:-

<!DOCTYPE html>
<html>
<head>
    <title>My node js app</title>
</head>
<body>
    <form action="/get" method="get">
        <h1>Welcome to Stock manipulation</h1><br></br>
        Select option<select>
        <option value=0>Get</option></select>
        <input type="submit" id="query" value="get Result">
</body>
</html>

And my get.html

<!DOCTYPE html>
<html>
<head>
    <title>Get</title>
</head>
<body>

</body>
</html>

And here is the data stored at database

[ RowDataPacket { id: 1, type: 'BSE' },
  RowDataPacket { id: 2, type: 'NSE' } ]

The error i am getting after Submitting the request isenter image description here

标签: node.jsexpresspostget

解决方案


改变

<form action="/get" method="get">

<form action="/get" method="post">

正如您定义的/get路线(app.post('/get',function(req,res){/*..*/})

只接受post请求

同样在您的/get路线处理程序中,您应该输出一些东西。现在你不输出任何东西,只登录到 node.js 控制台


推荐阅读