【问题标题】:HTML Form data to MySQL using Node JS not working使用 Node JS 到 MySQL 的 HTML 表单数据不起作用
【发布时间】:2019-05-05 16:56:02
【问题描述】:

我一直在使用nodejs练习一个简单的html表单到mysql,但它似乎不起作用,html称为index.html,我的nodejs文件称为test.js,这是我的代码:

我的html

<!DOCTYPE html>
<html>
<head>
<title>email test form</title>
</head>
<body>

<form method="post" action="/data">
<label for="email">Voer je email in </label> <input type="email" 
name="email"></input>
<input type="submit" value="submit">
</form>

<script src="test.js"></script>

</body>
</html>\

我的节点 js javascript:

var express = require('express');
var app = express();
var mysql =  require('mysql');
var bodyParser = require ('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));

var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Bionicle123!",
database: "account"
});

con.connect(function(err){ 
if (err) throw err;
console.log("Je bent verbonden aan de database!");
});

app.post("/data", function(req, res) {
var userEmail = req.body.email;

console.log(userEmail);

var sql = "INSERT INTO persoon (email) VALUES (?)";
con.query(sql, userEmail, function (err, data) {
    if (err) {
        console.log("Failed ah mattie!");
    } else {
        console.log("Gelukt ah mattie!");
    }
});
});

【问题讨论】:

  • “它似乎不起作用”是an unhelpful description of the problem。发生什么了?有错误信息吗? console.log(userEmail); 记录了什么?回调函数记录什么?
  • 它只是不起作用,当我在表单中输入电子邮件并提交时,它不会进入 mysql 数据库,console.log(userEmail) 没有显示任何内容。
  • 这表明浏览器正在请求错误的 URL。查看浏览器开发者工具中的网络标签。
  • Uncaught ReferenceError: require is not defined at test.js:1
  • 我想不出任何不支持require 的Node.js 版本。您必须尝试在不是 Node.js 的东西中运行您的脚本。

标签: javascript html mysql node.js forms


【解决方案1】:

Uncaught ReferenceError: require is not defined at test.js:1

您已标记此问题

您需要使用 Node.js 运行您的 JavaScript。

https://nodejs.org/en/ 下载它,然后安装它,然后运行 ​​node test.js

不允许加载本地资源:file:///C:/newuser

您需要从使用 Node.js 编写的网络服务器加载 HTML 文档。否则action URL 不会指向正确的位置。

……但首先你需要完成 Web 服务器的编写。查看 the Hello World example 的 Express.js(您也在使用)。

您需要致电listen。这将为您提供一个指向浏览器的 URL。

【讨论】:

  • 我已经安装了 nodejs,当我尝试手动将 js 文件中的数据输入到 mysql 时它可以工作,但现在我正在尝试将 nodejs 的 html 输入到 mysql 工作。
  • @Pakjethee — 那么答案的后半部分应该可以解决问题。
  • 现在我在 chrome 网络中收到此错误:HTTP 错误 405 无法加载资源:服务器响应状态为 405(不允许方法)
  • 不应该。你有 app.post("/data" 匹配 &lt;form method="post" action="/data"&gt;。再次检查网络选项卡,看看请求是否有任何问题。
  • 我应该将其设置为 localhost:8080 吗?当我查看我的 mysql 工作台时,我看到端口是 3306
猜你喜欢
  • 2015-09-19
  • 2014-02-28
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 2016-04-26
  • 2022-01-08
相关资源
最近更新 更多