Reputation: 6697
Here is my code:
var url = "http://quotes.toscrape.com/";
var express = require('express');
var request = require('request');
request(url, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
var re = new RegExp('<title>(.*)</title>');
var r = body.match(re);
if (r)
console.log(r[1]);
});
When I execute this command: node index.js
I will see the result (the title of that website) in the command line environment as well. But I want to see the result in the browser. How can I do that?
Noted that months ago, I was working on a react project and If I recall correctly I was able to see the result on the browser (localhost:3000
) by executing npm start
. But I don't know why it doesn't happen for this project.
Upvotes: 0
Views: 3842
Reputation: 492
You can use an express server to send the response to browser.
var url = "http://quotes.toscrape.com/";
var express = require('express');
var request = require('request');
var app = express();
app.get('/your-route', function(req, res) {
request(url, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
var re = new RegExp('<title>(.*)</title>');
var r = body.match(re);
if (r) {
res.write(r[1]);
res.end();
}
});
})
app.listen(3000);
Upvotes: 1
Reputation: 1894
Here is an example of creating an app with express
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Also request
is only usefull for making http calls, not creating any kind of server
Upvotes: 1
Reputation: 4103
You can using socket.io
.
If you want browser run console.log(r[1]);
, you use socket.emit('log', r[1]);
.
In browser (in javascript of your html file):
socket.on('log', ...data=>{
console.log(...data);
});
But you should read https://socket.io/ to config and understand it.
Upvotes: 1
Reputation: 327
To access anything from the browser you need to create an express app and call listen()
on it.
const express = require('express')
const app = express();
app.get('/', function (request, response) {
// Process request and form a response
response.send(/*response*/);
});
app.listen(3000, () => console.log('Listening on port 3000');
Upvotes: 0