var Request = require("request");
Request.get("https://www.yonline.com", (error, response, body) => {
if(error) {
return console.dir(error);
}
document.getElementById('msg').innerHTML=JSON.parse(body)
console.dir(JSON.parse(body));
});
I tried this code, but it is only giving data on the command line. i want it to give data on the intended textfield.
NodeJS is server side script you can't access HTML element like this.
You need to do it on html javascript side.
Related
app.get("/view", (req, res) =>{
request('https://corona.lmao.ninja/countries', (error, response, body) => {
console.error('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
return res.send(body);
});
});
I have this code working and it gives me an json in my browser. I am new to programing and have no idea how i put this in html or javascript to make a nice looking website.
Start simple. First determine if the body coming back from request() is an object or a string. If it's a string, then you need to parse is using obj=JSON.parse(body) to get an object.
From there you can try the quick and dirty:
res.send(`<html><body>Hi! Here is my json: <span color='red'> ${JSON.toString(obj)}</span></body></html>`)
That should get you started. The next step would be to output various obj fields to separate HTML elements (spans, divs, tables, whatever).
An easier way to do this would be to create a webpage that receives the data from https://corona.lmao.ninja/countries and formats the data using a script.
This should help with that: How to make a JSON call to a url?
If you still want to do it the way you did it above, you should create a separate HTML page that loads the data from /view, then formats it. You should do this on the webpage by using the Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
obj=JSON.parse(body)
var jsonstr=JSON.stringify(obj)
document.body.innerHTML=jsonstr
I have written the piece of code below:
static async postSearchResult(httpContext: HttpContext, injector: Injector) {
const log = injector.get(Log);
const service = injector.get(Service);
try {
let result = await service.redirectToUI(JSON.parse(httpContext.getRequestBody()));
httpContext.ok(result, 200, {'Content-Type': 'application/json'});
} catch (e) {
httpContext.fail(e, 500);
}
}
protected redirectToUI(response: any) {
// If any post api call happened then it should open web browser and pass some field as query parameter
window.open("https://www.google.com?abc=response.abc");
return response ? response : "failed";
}
Here I am getting the following error :
Execution failed ReferenceError: Window is not defined
What am I doing wrong?
What you are trying to accomplish doesn't make much of a sense. Lambda is a back-end service. To open new browser window, you need to use front-end JavaScript, not back-end Node (on the back-end, you have no access to the front-end window object).
If you want to open a new browser window as a reaction to some back-end response, then you can send some indicator in the HTTP response (i.e shouldOpenNewWindow: true as a part of the response object), parse that response on the front-end and it the indicator is present, then you can issue window.open command. But it has to be done on front-end.
I want to send form data which is coming from my angularjs form to nodejs and then I want to send these data from nodejs to my service API. But the data is not receiving at my service API. I cannot understand what was going wrong in this. Please help me to overcome this problem.
requestMethodDelete: function (url, form_data, header) {
return new Promise((resolve, reject) => {
console.log("FORM DATA IN DELETE REQUESST METHOD");
console.log(form_data);
//SET ALL THESE PARATMETER TO MAKE REQUEST
request.delete({url: url, form: form_data, headers: header},
function (error, response, body) {
resolve(body);
}
});
});
},
I want to send form data and header but couldn't receive at service API, please tell me what can I do for my expected result.
In request.delete function form option is not work for sending form_data. To sending form-data to our service api we need to use qs option rather than form option. that's it, it solved your problem also if you are facing the same problem which I was facing.
I would like to scrape the http://www.euromillones.com.es/ website to get the last winning 5 numbers and two stars. It can be seen on the left column of the website. I've been reading tutorials, but I am not capable of achieving this.
This is the code I wrote so far:
app.get('/winnernumbers', function(req, res){
//Tell the request that we want to fetch youtube.com, send the results to a callback function
request({uri: 'http://www.euromillones.com.es/ '}, function(err, response, body){
var self = this;
self.items = new Array();//I feel like I want to save my results in an array
//Just a basic error check
if(err && response.statusCode !== 200){console.log('Request error.');}
//Send the body param as the HTML code we will parse in jsdom
//also tell jsdom to attach jQuery in the scripts and loaded from jQuery.com
jsdom.env({
html: body,
scripts: ['http://code.jquery.com/jquery-1.6.min.js ']
}, function(err, window){
//Use jQuery just as in a regular HTML page
var $ = window.jQuery;
res.send($('title').text());
});
});
});
I am getting the following error:
Must pass a "created", "loaded", "done" option or a callback to jsdom.env.
It looks to me that you've just used a combination of arguments that jsdom does not know how to handle. The documentation shows this signature:
jsdom.env(string, [scripts], [config], callback);
The two middle arguments are optional but you'll note that all possible combinations here start with a string and end with a callback. The documentation mentions one more way to call jsdom.env, and that's by passing a single config argument. What you are doing amounts to:
jsdom.env(config, callback);
which does not correspond to any of the documented methods. I would suggest changing your code to pass a single config argument. You can move your current callback to the done field of that config object. Something like this:
jsdom.env({
html: body,
scripts: ['http://code.jquery.com/jquery-1.6.min.js'],
done: function (err, window) {
//Use jQuery just as in a regular HTML page
var $ = window.jQuery;
res.send($('title').text());
}
});
I am using this API to consume a ESPN API:
http://api.espn.com/v1/now?apikey=d4skkma8kt2ac8tqbusz38w6
In Node.js, using node-curl library, my snippet looks like this:
var Curl = require('node-curl/lib/Curl')
curl.setopt('URL', url);
curl.setopt('CONNECTTIMEOUT', 2);
curl.on('data', function(chunk) {
console.log(chunk);
});
But everytime when I run this code I keep on getting response as:
<h1>596 Service Not Found</h1>
Strange is, same URL if I hit from the browser I get the correct response so URL is not invalid. This happens only if I try to call from Node.js. Can anyone guide me how to resolve this error? I tried encoding/decoding url, still I get same response.
Also basically I am avoiding any vendor specific libraries as much as possible, since we should have generic api calling framework
You could use request, which is a very popular module. Here's an example of how you could do it:
var request = require('request');
var url = 'http://api.espn.com/v1/now?apikey=d4skkma8kt2ac8tqbusz38w6';
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body));
}
});