<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Node Express</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h3> My First Express Server... </h3>
<form action="/users" method="post">
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" name="name" id="usr">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="pwd">
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" name="comment" id="comment"></textarea>
</div>
<label class="radio-inline">
<input type="radio" name="optradio" value="1">Option 1</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="2">Option 2</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="3">Option 3</label>
<br>
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
JS文件:
var express = require('express')
var bodyParser = require("body-parser");
var app = express()
var sqlite3 = require('sqlite3').verbose()
//memory database use string filename for a persistant file.
var db = new sqlite3.Database(':memory:')
//now any files in public are routed
app.use(express.static('public'))
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
// REST endpoint for posting a new user
app.post('/users', function (req, res, next) {
let username = req.body.name;
let password = req.body.password;
let comment = req.body.comment;
let optradio = req.body.optradio;
var stmt = db.run(
`INSERT OR IGNORE INTO users VALUES ("${username}", "${password}", "${comment}", "${3}")`
)
db.all('SELECT * FROM users', function (err, row) {
res.json(row)
})
console.log("Just received POST data for users endpoint!");
console.log(`Data includes: ${username}, ${password} and ${comment} and ${optradio}`);
});
//set up table
db.serialize(function (){
db.run('CREATE TABLE IF NOT EXISTS users (name text UNIQUE, password text, comment text, option integer);')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
你这个没头没尾的,先把代码格式化下以及把你的需求说清楚。
感觉你想问node.js将表单里的内容存入数据库,是这个需求么?
看下这个程序:https://blog.csdn.net/kongjunchao159/article/details/50232741