简体   繁体   中英

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 is在此处输入图像描述

change

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

to

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

as you have defined the /get route ( app.post('/get',function(req,res){/*..*/}) )

to accept only post requests

Also in your /get route handler you should output something. Right now you do not output anything, only log to the node.js console

What is your nodejs server saying? In your routes you typically want to return some data. for example in your case your /get route res.send(data). that way your front end can show the data received. Also looks like you need to change your form to be a post not a get (Edit: As Nikos M. mentioned).

If you are new to http requests I recommend downloading Postman to get used to testing your routes requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM