【问题标题】:How to send HTML as a response in REST?如何在 REST 中将 HTML 作为响应发送?
【发布时间】:2020-04-16 02:28:20
【问题描述】:

我在Nodejs 中创建了一个API。我尝试创建一个返回 HTML 的调用以在浏览器中显示一个站点。

我的电话如下所示:

router.get('/displayHTML', checkAccessToken, (req, res, next) => {

if (req.query.data === undefined) {
    return res.status(900).json({
        message: 'Data does not exist'
    });
}

Data.find({ data: req.query.data}).exec()
    .then(data => {
        if (data.length < 1) {
            return res.status(400).json({
                message: "Nothing found"
            });
        }
        // I need to return HTML here so the user sees something in his browser
        return res.status(200).json({
            data: data

        });

    }).catch(error => {
        return res.status(500).json({
            message: error
        });
    });



});

【问题讨论】:

标签: html node.js rest


【解决方案1】:

检查 fs_library:https://nodejs.org/docs/v0.3.1/api/fs.html

var http = require('http'),
lib = require('fs');
lib.readFile('./page.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多