简体   繁体   English

Node.js 和 express (MySQL):无法在浏览器中发布 / 和 404 代码

[英]Node.js and express (MySQL): Cannot POST / and 404 code in browser

I'm just learning how to make a simple web-application for my dorm that would assign each participant a random number once they enter their name.我只是在学习如何为我的宿舍制作一个简单的网络应用程序,一旦他们输入他们的名字,它就会为每个参与者分配一个随机数。 There is a form field with one text box and a button.有一个带有一个文本框和一个按钮的表单域。 The text box (form) needs to send the full name (a single string) to the MySQL database so that later on I could retrieve the full list with the assigned numbers to actually use the application in the real world.文本框(表单)需要将全名(单个字符串)发送到 MySQL 数据库,以便稍后我可以检索带有分配数字的完整列表,以便在现实世界中实际使用应用程序。 Just for redundancy, I've put in code that creates a new database and a table every time, but then SQL ignores it if the DB and table already exist.只是为了冗余,我已经输入了每次创建一个新数据库和一个表的代码,但是如果数据库和表已经存在,SQL 会忽略它。

My fundamental problem is that I can not get data from my form in HTML.我的根本问题是我无法从 HTML 中的表单中获取数据。 I'm using express.js and am trying to retrieve it, then post it into my database via the SQL module.我正在使用 express.js 并尝试检索它,然后通过 SQL 模块将其发布到我的数据库中。 Now as I'm a complete newbie, I have no idea how it should work.现在,由于我是一个完整的新手,我不知道它应该如何工作。 For the past 4 days, I've searched all over the internet to try to solve this issue.在过去的 4 天里,我一直在互联网上搜索,试图解决这个问题。 I don't know if the js document is the problem or the HTML document.不知道是js文档的问题还是HTML文档的问题。

This is my HTML form (do tell me if you would need the whole thing):这是我的 HTML 表格(请告诉我您是否需要整个表格):

<form action="/createPerson" method="POST">
                <input type="text" name="name" value="Ime in priimek">
                <input type="submit" name="name" value="Potrdi" class="gumbek">
            </form>

And here is my complete node.js document:这是我完整的 node.js 文档:

 var mysql = require('mysql'); var express = require("express"); var bodyParser = require("body-parser"); var urlencodedParser = bodyParser.urlencoded({ extended: false }); const http = require('http'); var fs = require('fs'); const app = express(); const path = require('path'); const router = express.Router(); // Unique random number generator module const uniqueRandom = require('unique-random'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); server = http.createServer(app); server.listen(); // Start connecting to MySQL database var con = mysql.createConnection({ host: "localhost", user: "root", password: "root", database: "mydb" }); //if database mydb exists, ignore database creation let createMydb = "CREATE DATABASE if not exists mydb" con.connect(function(err) { if (err) throw err; console.log("Connected;"). con,query(createMydb, function(err, result) { if (err) throw err. console;log("Database already exists."), console;log("Database OK (Already exists; will not create new one)"); }), }), //if table person exists, ignore table creation let createTable = "CREATE TABLE if not exists person (id INT AUTO_INCREMENT PRIMARY KEY; name VARCHAR(255); number VARCHAR(255))". var sql = createTable, con,query(sql, function(err. result) { if (err) throw err, console;log("Table exists. will not create new table"), console;log("Table OK (Already exists. will not create new one)"); console.log('Running at Port 3000'). console.log("Connected; Commencing value input into database:"). //var post = { name. req,body:name. number, random } //app,get('/createPerson', urlencodedParser, function(err; req. res) { if (err) throw err. //res(req;body.name) }), router,get('/'. function(req. res) { res.sendFile(path;join(__dirname + '/index:html')). //__dirname; It will resolve to your project folder, }); /*const random = uniqueRandom(1, 100); const values = ['/createPerson', String(random())]? var insert = "INSERT INTO person (name. number) VALUES (,)" con,query(insert, [values]; function(err. result) { if (err) throw err. console;log("Value was inserted into database;"). }),*/ app,get('/createPerson'. function(req; res) { res.render('form'). // if jade // You should use one of line depending on type of frontend you are with res;sendFile(__dirname + '/index;html'). //if html file is root directory }), app,post('/createPerson', urlencodedParser, function(req; res) { const random = uniqueRandom(1. 100). const values = [String(req,body;name), String(random())]? var insert = "INSERT INTO person (name. number) VALUES (.)" console.log(req;body.name), con,query(insert, [values]; function(err. result) { if (err) throw err. console;log("Value was inserted into database."). res;sendFile(__dirname + '/numberAssigned.html'); res;end(); }); });

Now every time I press the button in the form, I get Cannot POST /createPerson inside the browser and no data was sent to my database.现在每次我按下表单中的按钮时,我都会在浏览器中得到Cannot POST /createPerson并且没有数据发送到我的数据库。 Browser (network tab) also gives me 404. Maybe it can't find the form?浏览器(网络选项卡)也给了我 404。也许它找不到表格?

I am a complete newbie at all of this, I can manage HTML and CSS, Javascript is something really new to me.我完全是新手,我可以管理 HTML 和 CSS,Javascript 对我来说真的很新鲜。 If you find the time to help me, THANK YOU FROM THE BOTTOM OF MY HEART!如果您有时间帮助我,我衷心感谢您!

The problem is that you are using node.js http module and express at the same time.问题是您同时使用node.js http 模块快递

You are setting up /createPerson within the express.js app, but starting the node.js http server instead.您正在 express.js 应用程序中设置 /createPerson,但改为启动 node.js http 服务器。 So, no end-points are present in the server you've started - hence 404 Page Not Found.因此,您启动的服务器中不存在任何端点 - 因此 404 Page Not Found。

Usually, you use just one of them.通常,您只使用其中之一。 Node.js http module provides an ability to start a low-level HTTP server. Node.js http 模块提供了启动低级 HTTP 服务器的能力。 Express, on the other hand, is a more high-level solution for building http services.另一方面,Express 是用于构建 http 服务的更高级的解决方案。 So in your case, I would stick with express and throw out http (express is using http module under the hood anyways).所以在你的情况下,我会坚持使用 express 并扔掉 http (express 无论如何都在引擎盖下使用 http 模块)。

But the fundamental problem of your solution is that it is too big and complex to bootstrap from scratch.但是您的解决方案的根本问题是它太大而复杂,无法从头开始引导。

It could be really confusing to figure out what is going on in a complex app, since you are trying to do many things at once - express http server + sql database + html forms... Many things can go wrong, so better try a "Hello World" approach instead. It could be really confusing to figure out what is going on in a complex app, since you are trying to do many things at once - express http server + sql database + html forms... Many things can go wrong, so better try a取而代之的是“Hello World”方法。

To debug a problem like that, I would downscale the app and try to check every little interaction level by level:为了调试这样的问题,我会缩小应用程序并尝试逐级检查每个小的交互:

Level 1 1级

  1. Comment out http module usage and every mapping in express except POST for /createPerson注释掉 http 模块用法和 express 中的每个映射,除了 /createPerson 的 POST
  2. Make sure you run express app.listen() after the end-point setup.确保在端点设置后运行 express app.listen()。
  3. Comment out all database access in /createPerson handler and leave just a log statement like that:注释掉 /createPerson 处理程序中的所有数据库访问,并只留下这样的日志语句:
    app.post('/createPerson', urlencodedParser, function(req, res) {
        console.log(req.body.name);
    }
  1. Now run your script with node.js and try to check the POST on /createPerson with curl:现在使用 node.js 运行您的脚本,并尝试使用 curl 检查 /createPerson 上的 POST:
    curl --data-urlencode "name=John Doe (Junior)" http://localhost:3000

(make sure you are using the right port) (确保您使用的是正确的端口)

  1. Check node.js logs - you have to see a name you're sending with curl in there.检查 node.js 日志 - 您必须在其中查看您发送的带有 curl 的名称。

When you see the name in logs, Level 1 is complete!当您在日志中看到名称时,级别 1 已完成!

Level 2 2级

Now try to do the same POST, but form an HTML form.现在尝试执行相同的 POST,但形成 HTML 表单。

  1. Add a static mapping on /public to node.js.将 /public 上的 static 映射添加到 node.js。

  2. Run the node.js server.运行 node.js 服务器。

  3. Open a page with the HTML form and POST it.使用 HTML 表单打开一个页面并发布它。

  4. Make sure your form is sending data to correct URL and you see the data in node.js logs确保您的表单正在发送数据以纠正 URL 并且您会在 node.js 日志中看到数据

Level 3 3级

Only now, when you have data flowing from html to node.js, you can try to extend the system with a database.只是现在,当您有数据从 html 流向 node.js 时,您可以尝试使用数据库扩展系统。 Reintegrate db access code back into /createPerson and debug the solution.将数据库访问代码重新集成回 /createPerson 并调试解决方案。

Good luck with the next levels!祝你在下一个级别好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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