我对节点js和创建一个简单的应用程序来查询存储在数据库(MySql) .So中的数据并不熟悉。我所做的是,我已经创建了一个名为.So的数据库,我正在使用index.html对其进行查询,以便在get.html中显示它,但是在执行get请求之后,我无法获得结果。这是我的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);
我的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>
还有我的get.html
<!DOCTYPE html>
<html>
<head>
<title>Get</title>
</head>
<body>
</body>
</html>
这是存储在数据库中的数据
[ RowDataPacket { id: 1, type: 'BSE' },
RowDataPacket { id: 2, type: 'NSE' } ]
在提交请求之后,我得到的错误是
发布于 2020-06-09 03:06:10
变化
<form action="/get" method="get">
至
<form action="/get" method="post">
正如您已定义的/get
路由(app.post('/get',function(req,res){/*..*/})
)
只接受post
请求
另外,在您的/get
路由处理程序中,您应该输出一些内容。现在,您不会输出任何内容,只会记录到node.js控制台
发布于 2020-06-09 03:08:07
你的nodejs服务器是怎么说的?在您的路由中,您通常希望返回一些数据。例如,在您的示例中,您的数据路由res.send( /get )。这样,您的前端就可以显示接收到的数据。看起来您还需要将表单更改为post而不是get (Edit:如Nikos M.所述)。
如果你是http请求的新手,我建议你下载Postman来测试你的路由请求。
https://stackoverflow.com/questions/62269354
复制相似问题