簡體   English   中英

無法進入Node Js

[英]Cannot Get in Node Js

我是節點 js 的新手,並創建了一個簡單的應用程序來查詢存儲在數據庫(MySql)中的數據。所以我正在做的是,我創建了一個名為 stock 的數據庫,我正在使用 index.html 查詢它以在獲取時顯示它。 html 但在執行獲取請求后我無法獲得結果。 這是我的 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);

我的索引.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>

還有我的get.html

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

</body>
</html>

這是存儲在數據庫中的數據

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

提交請求后我得到的錯誤是在此處輸入圖像描述

改變

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

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

正如您已定義/get路線( app.post('/get',function(req,res){/*..*/})

只接受post請求

同樣在您的/get路由處理程序中,您應該 output 一些東西。 現在你沒有 output 任何東西,只登錄到 node.js 控制台

你的nodejs服務器在說什么? 在您的路線中,您通常希望返回一些數據。 例如,在您的情況下,您的 /get route res.send(data)。 這樣您的前端就可以顯示收到的數據。 看起來您還需要將表單更改為帖子而不是獲取(編輯:正如 Nikos M. 提到的)。

如果您不熟悉 http 請求,我建議您下載 Postman 以習慣測試您的路線請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM