我正在尝试以下操作:
在中具有端点 Express.js 打电话 /content.json 。当我调用该端点时,我希望在标签中显示HTML。
Express.js
/content.json
我有以下服务器代码:
var http = require('http'); var express = require('express'); var request = require("request"); var app = express(); var port = 4000; app.listen(port); console.log('Listening on port',port); app.use("/assets",express.static(__dirname+ '/assets')); app.get('/content.json',function(req,res) { request("http://www.google.com", function(error, response, body) { res.data = body; }); });
我有以下客户端代码:
<input type="button" text="Get content" id="googleBtn" value="Get google" /> <label id="contentLbl" /> <script> $('#googleBtn').click(function() { $.ajax({ url: '/content.json', type: 'GET', contentType: 'application/json', success: function(jsonData) { $('#contentLbl').text(jsonData.data); } }); }); </script>
但我的js控制台中的请求似乎是空的。
如何修改服务器/客户端以在标签中获取Google.com的HTML?:)
免责声明:完全是Node.js新手
您需要从服务器代码发送数据:
app.get('/content.json',function(req, res) { request("http://www.google.com", function(error, response, body) { res.send(body); }); });
编辑: 由于JS客户端需要appination/json,因此您还应该设置从服务器发送的响应头:
res .header('Content-Type', 'application/json') .send(body);