I am trying to do something the following:
Have an endpoint in Express.js called /content.json. When I call that endpoint, I want to show the HTML in a label.
I have the following server code:
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;
});
});
I have the following client code:
<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>
But it seems the request is empty in my js console.
How do I modify server/client to get the HTML of Google.com in my label? :)
Disclaimer: totally newb to Node.js
You need to send the data out from the server code:
app.get('/content.json',function(req, res) {
request("http://www.google.com", function(error, response, body) {
res.send(body);
});
});
Edit: As the JS client is expecting appication/json, you should set the response header sent from server as well:
res
.header('Content-Type', 'application/json')
.send(body);