express + handlebars 学习遇到的小坑

 

最近想系统学习一下express,所以找来大师的《Node与Express》膜拜,问题不少,记录下来,供大家参考交流:

1  模板渲染上下文的赋值 res.locals

是这么个情况:


模板文件views/partials/weather.hbs

<div class="weatherWidget">
    {{#each partials.weather.locations}}
        <div class="location">
            <h3>{{name}}</h3>
            <a href="{{forecastUrl}}">
                <img src="{{iconUrl}}" alt="{{weather}}"> {{weather}}, {{temp}}
            </a>
        </div>
    {{/each}}
    <small>Source: <a href="http://www.wunderground.com">Weather Underground</a></small>
</div>

应用文件meadowlark.js

/* 给res.locals.partials对象添加数据的中间件 */
app.use(function(req, res, next){
    if(!res.locals.partials) res.locals.partials = {};
    res.locals.partials.weather = getWeatherData();
    next();
});


//获得天气数据
function getWeatherData(){
    return {
        locations:[
            {
                name:'Portland',
                forecastURl:'http://www.wunderground.com/US/OR/Portland.html',
                iconUrl:'http://icons-ak.wxug.com/i/c/k/cloudy.gif',
                weather:'Overcast',
                temp:'54.1.F(12.3 C)'
            },
            {
                name:'Bend',
                forecastURl:'http://www.wunderground.com/US/OR/Bend.html',
                iconUrl:'http://icons-ak.wxug.com/i/c/k/partlycloudy.gif',
                weather:'Partly Cloudy',
                temp:'55.0.F(12.8 C)'
            },
            {
                name:'Manzanita',
                forecastURl:'http://www.wunderground.com/US/OR/Manzanita.html',
                iconUrl:'http://icons-ak.wxug.com/i/c/k/rain.gif',
                weather:'Light Rain',
                temp:'55.0.F(12.8 C)'
            }
        ]
    }
}

运行  node meadowlark.js 就会报错

Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed [object Object]

查了一些资料,感觉都是客户端用handlebars没有compile 模板源码才会这样,但我是服务端渲染啊,咋也这样?后来,查看书上的源码,发现有一个单词不一样,源码没有用weather,而是weatherContext,进过测试,除了weather,别的都可以,貌似是和handlebars文件名冲突了,我只能想到这了,虽然还没有找到正确的解释,但问题是找到了

贴出可以运行通过的代码:

views/partials/weather.hbs

/* 给res.locals.partials对象添加数据的中间件 */
app.use(function(req, res, next){
    if(!res.locals.partials) res.locals.partials = {};
    res.locals.partials.weatherContext = getWeatherData();
    next();
});

 

应用文件meadowlark.js 

<div class="weatherWidget">
    {{#each partials.weatherContext.locations}}
        <div class="location">
            <h3>{{name}}</h3>
            <a href="{{forecastUrl}}">
                <img src="{{iconUrl}}" alt="{{weather}}"> {{weather}}, {{temp}}
            </a>
        </div>
    {{/each}}
    <small>Source: <a href="http://www.wunderground.com">Weather Underground</a></small>
</div>

2  post表单的重定向处理

express 4.x的api中 res.redirect([status,] path),默认的status是302,

但302和303(HTTP1.1)还是有区别

来自维基百科:

302 Found:

The HTTP response status code 302 Found is a common way of performing URL redirection.

The HTTP response status code 302 Found is a common way of performing URL redirection.Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g. POST).For this reason, HTTP/1.1 (RFC 2616) added the new status codes 303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of request type to GET, and 307 preserving the request type as originally sent.

也就是说302表示找到了,但如果是post请求,重定向url就会为get,修改了请求类型,这种情况,要用303,表示找到了另一个

所以,如果是post表单,303重定向告诉浏览器:你的请求有效,可以在这里找到响应

3 AJAX表单

处理post请求,最好要区分是AJAX还是一般表单提交,有两个属性可以判断:

req.xhr 和 req.accepts(type) ,前者判断是否是AJAX请求,后者判断HTTP Request 头信息合适的返回类型

这里假定AJAX请求的数据都是json

app.post('/process',(req,res)=>{
    console.log(req.accepts('json,html'));
   if(req.xhr || req.accepts('json,html') === 'json'){
       //如果错误,发送{error:'error message'}
       res.json({success:true})
   }else{
       res.redirect(303,'/thank-you');
   }
});

 

 

参考:

1 http://expressjs.com/en/4x/api.html

2 https://en.wikipedia.org/wiki/HTTP_302

3 https://en.wikipedia.org/wiki/HTTP_303

4 https://github.com/EthanRBrown/web-development-with-node-and-express/blob/master

 

转载于:https://my.oschina.net/u/2510955/blog/692551

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值