如何在 REST 中发送 HTML 作为响应? [英] How to send HTML as a response in REST?

查看:68
本文介绍了如何在 REST 中发送 HTML 作为响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created an API in Nodejs. I have tried creating a call which returns HTML to display a site in the browser.

我的电话看起来像这样:

My Call looks like this:

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



});

推荐答案

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

Check the 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);
});

这篇关于如何在 REST 中发送 HTML 作为响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆