var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = 3000;
const fs = require('fs');
// we are connecting to the mangodb using mangoose
var mongoose = require("mongoose");
// Now we are using bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
// now we are creating the schema to the database
var nameSchema = new mongoose.Schema({
firstName: String,
lastNameName: String
});
// Now we have to create a model
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
1)我正在使用express app.post将数据发布到数据库中,并将数据存储到写入文件中进行检查
2)app.post无法正常工作,它尝试了console.log进行检查,但没有进入功能
3)我没有得到输出,请帮助我解决任何错误
答案 0 :(得分:0)
此代码中没有错误处理和响应处理。
如果我们用post
编写async/await
方法,那将是可读的:
app.post("/addname", async (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
await myData.save()
console.log(myData);
fs.writeFileSync(__dirname +"/data.json", myData)
console.log(myData)
})
答案 1 :(得分:0)
这是因为每个请求都将转到此app.use
代码块。 app.use("/", (req, res) => { ... });
只需将其放在app.post("/addname", (req, res) => { ... });
app.use
用于将middlewares装入请求-响应链。因此,每个与/
(实际上是每个请求)匹配的请求都进入该中间件内部。因此,请先使用您的路由,然后最后使用中间件。
希望这会有所帮助。
编辑:
让我给你一个mcve,我在本地进行了测试:
const express = require('express');
const fakeData = function(){
return {
s: "fakeData"
}
}
const app = express();
const port = 8181
const path = require('path')
app.get("/a", (req, res) => {
return res.json({d:'yay'});
});
app.use('/',(req,res)=>{
return res.json(fakeData());
})
app.listen(port, () => {
console.log(`Server started on PORT ${port}`);
});
因为每个请求都通过已安装的中间件,所以当您GET
/ POST
/任何东西到 localhost:8181/<abosulutely_any_path>
时,它将通过{{1} },因为它将该函数视为中间件,并且将返回app.use
。
但是,当您拨打{ s: "fakeData" }
呼叫 GET
时,它将转到http://localhost:8181/a
路由因为我们首先声明了它,返回app.get