I am currently trying to learn Node.js and implementing my first API (I picked Chuck Norris API) in SAP Web IDE. The following is the code that I found:
app.get("/chuckvar", (req, res) => {
var http = require('https'),
url = require('https://api.chucknorris.io/jokes/random');
http.createServer(function (req, res) {
var query = url.parse(req.url, true).query;
res.end(JSON.stringify(query));
});
});`
Until now I was able to display the content of the URL in the console but not on the browser which is my goal.
I wrote this code but I keep getting the same Error message.
So I need help to successfully implement the API.
The "require" function purpose is to import modules (like the https one when you do require('https')
).
Your error message means that "require" expected the argument to be a node module (not an url).
To fetch an url content you can use the "request" module (witch is simpler to use that the native one):
const request = require('request');
app.get("/chuckvar", (req, res) => {
request('https://api.chucknorris.io/jokes/random', 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
console.log('body:', body); // Prints the body
res.end(body); // Will forward the api response
});
});