我正在从index.js节点文件中的index.html文件中的输入中获取未定义的数据,并且想知道如何将在html中的input元素中输入的文本获取到我的数据库中
我对整个后端事物还是陌生的,所以不知道尝试什么,但是我一直在遵循编码培训视频,这对我有所帮助
const express = require('express');
const Datastore = require('nedb');
const database = new Datastore({filename: 'users.db'});
database.loadDatabase((data_response) => {
data_response = 'The database is active'
console.log(data_response);
});
const app = express();
const PORT = 8080;
const run_server = () => {
app.listen(PORT);
app.use(express.static('public'));
console.log('Server is lve at port: ', PORT);
}
run_server();
app.use(express.json({limit: '1mb'}));
app.post('/api', (request, response) => {
console.log('***********************************');
console.log('\t Got a request');
console.log('\t', response.body);
let user_data = response.body;
database.insert(user_data);
response.json({
result: 'Succes',
userData: user_data
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<h1>send data to nedb database</h1>
<textarea name="enter" id="text" cols="30" rows="10"></textarea>
<button type="submit" id="submit">Submit</button>
</div>
<script>
let data = document.getElementById('text').value;
document.getElementById('submit').addEventListener('click', () => {
let options = {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('/api', options);
});
</script>
</body>
</html>