几点建议
关于index.html中的ajax调用
- If your
index.html
由同一服务器提供服务,请不要使用跨域调用。这url
财产在$.ajax
可能是一个相对网址,例如/start
.
- 您也可以考虑不使用
jsonp
要求。
电话可能是这样的
$.ajax({
dataType: 'json',
data: $('#formID').serialize(),
type: 'POST',
url: "./start",
success: handleButtonResponse,
});
JSON 如何/从哪里连接到 MongoDB?
在你请求的ajax调用中./start
,所以你的express服务器中应该做同样的路由。喜欢
app.get('/start', function (req, res) {
db.collection('collectionName').insert({req.data}, function (err, doc) {
//rest of code
});
});
Express 是否需要模板引擎,例如 Consolidate?如果是这样,它如何/在哪里适合?
你有很多模板选择,比如 jade、ejs、hbs 等等。
如果您使用 jade 或其中任何一个,您在快速路由中的 html 渲染代码将会得到简化。
没有模板引擎
response.writeHead(200, {"Content-Type:": "application/json"});
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.write( "_wrapper('" );
response.write( JSON.stringify(submittedPost) );
response.write( "')");
response.end();
使用 jade(现在是哈巴狗)这样的模板引擎
var submittedPost = {};
submittedPost['message'] = 'Proof that Node and Mongo are working..';
response.json(submittedPost);
另外,使用模板引擎,您可以使用服务器端变量渲染模板,并且可以在模板中访问它们,例如
app.get('/mypage', function (req, res) {
res.render('mytemplate_page',{template_variable:some_variable});
});
你可以使用template_variable
在模板内用于循环或显示。