node.js - 在 Azure Web 应用程序中解析表单数据
问题描述
我在 azure 上测试了一个 nodejs Web 应用程序,它使用 azure cosmos db 插入和检索数据。Web 应用程序基于 express 框架、mongoose(用于数据库交互)、用于模板的 pug 和用于解析 Web 表单发送的数据的 body-parser。
我遇到的问题是无法访问web表单发送的数据,我想根据这些数据在azure cosmos db中插入一个新文档。基本上,当我提交 Web 表单时,应用程序应该访问表单数据(在body-parser模块的帮助下),在数据库中创建一个新文档并刷新视图(其中将包含来自新创建的文档的信息)。
下面是这个小应用程序的代码。
const express = require('express');
const http = require('http');
const mongoose= require('mongoose');
const bodyParser = require('body-parser');
const app = express();
var port = process.env.PORT || 5050; //normalizePort(process.env.PORT || '5050');
app.set('port', port);
app.set('views', 'views');
app.set('view engine', 'pug');
mongoose.connect(`mongodb://[user].documents.azure.com:10255/testdb?ssl=true`, {
auth: {
user: `[username]`,
password: `[password]`
}
})
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
let citySchema = new mongoose.Schema ({
id: {type: String, required: true},
name: {type: String, required: true},
country: {type: String, required: true}
});
const Cities = mongoose.model('Cities', citySchema);
let getData = function(request, response) {
Cities.find({}, function(err, data) {
if (err) { return "There was an error";}
console.log(JSON.stringify(data));
response.render('index', {
panelTitle: "Azure CosmosDB Test",
panelBody:"Testing how to access Azure ComsosDB",
cities: data
});
});
};
let urlencoded = bodyParser.urlencoded({extended: false});
app.get('/', function(request, response) {
getData(request, response);
});
app.get('/error', function(request, response) {
response.render('error');
})
app.post('/', urlencoded, function(request, response){
console.log(request.body);
let newCity = new Cities({id: request.body.id, name: request.body.name,
country: request.body.country});
console.log(newCity);
newCity.save(function(err, savedCity){
console.log(JSON.stringify(savedCity));
});
response.redirect('back');
});
app.use(express.static(__dirname + '/public'));
const server = http.createServer(app);
server.listen(port);
在 localhost 上,代码工作得很好,它将新文档插入数据库,然后在刷新的视图中,新城市出现在列表中(基于 pug 文件生成)。
但是在 Azure 上什么也没发生。视图已刷新,但未创建新文档,当然该视图不包含 Web 表单发送的信息。数据库连接不是问题,因为该应用程序能够提取信息以生成城市列表。此外,如果在发布路线中,当我创建一个新城市并尝试保存它时,我会使用如下直接值:
let newCity = new Cities({id: 'MUN", name: "Munich",
country: "Germany"});
该文档已创建并保存在 azure cosmos db 中,并且视图包含新数据。
在我看来,req.body是空的,并且没有解析表单数据,尽管我在这方面使用了body-parser模块。在开发人员工具的浏览器中 - 网络选项卡 - 显示发送到服务器的表单数据,我的状态代码为 302。
如果您知道为什么这不适用于 azure,请告诉我。
谢谢!
解决方案
确保您已使用语句app.use(bodyParser.json());
使 bodyParser 识别您的 json 数据。
没有它,我会得到与您相同的空结果{}
。
BodyParser 不能告诉传入的正文格式,除非我们指定它。