如何在REST中发送HTML作为响应?

时间:2019-12-25 12:23:33

标签: html node.js rest

我已经在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
        });
    });



});

2 个答案:

答案 0 :(得分:2)

您可以返回HTML,如下所示:

res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<html>Hello World</html>')
        res.end()

答案 1 :(得分:2)

检查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);
});