菜鸟教程小白 发表于 2022-12-11 20:20:58

node.js - 提供多种内容类型


                                            <p><p>我正在使用 Express 创建网站和 API,我想在同一路径上提供多种内容类型(JSON、XML、HTML)。在 Express 中是否有更好的方法来编写以下内容:</p>

<pre><code>// Serve JSON requests
app.get(&#39;/items/&#39;, function(req, res, next){
    if(!req.accepts(&#39;application/json&#39;)){
      return next();
    }

    res.end();
});

// Serve XML requests
app.get(&#39;/items/&#39;, function(req, res, next){
    if(!req.accepts(&#39;application/xml&#39;)){
      return next();
    }

    res.end(&#39;&lt;items&gt;&lt;item&gt;1&lt;/item&gt;&lt;item&gt;2&lt;/item&gt;&lt;item&gt;3&lt;/item&gt;&lt;item&gt;4&lt;/item&gt;&lt;item&gt;5&lt;/item&gt;&lt;/items&gt;&#39;);
});

// Serve HTML requests
app.get(&#39;/items/&#39;, function(req, res, next){
    if(!req.accepts(&#39;text/html&#39;)){
      return next();
    }

    res.end(&#39;&lt;ul&gt;&lt;li&gt;1&lt;/li&gt;&lt;li&gt;2&lt;/li&gt;&lt;li&gt;3&lt;/li&gt;&lt;li&gt;4&lt;/li&gt;&lt;li&gt;5&lt;/li&gt;&lt;/ul&gt;&#39;);
});
</code></pre>

<p>特别是,上面的代码似乎相当重复,可能有更标准的写法。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>有一个 response.format 方法,它使用基于“Accept” header 选择某些渲染方法。 <a href="http://expressjs.com/4x/api.html#res.format" rel="noreferrer noopener nofollow">http://expressjs.com/4x/api.html#res.format</a> </p>

<p>响应可能如下所示:</p>

<pre><code>res.format({
text: function(){
    res.send(&#39;hey&#39;);
},

html: function(){
    res.send(&#39;hey&#39;);
},

json: function(){
    res.send({ message: &#39;hey&#39; });
}
});
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于node.js - 提供多种内容类型,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/51230142/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/51230142/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: node.js - 提供多种内容类型