express + handlebars 学习遇到的小坑

丶灬走出姿态 提交于 2020-12-02 05:37:09

 

最近想系统学习一下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

     

    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!