简体   繁体   English

如何使用Node.js在SCP中实现API并在浏览器上显示

[英]How to implement an API in SCP with Node.js and display on Browser

I am currently trying to learn Node.js and implementing my first API (I picked Chuck Norris API) in SAP Web IDE. 我目前正在尝试学习Node.js,并在SAP Web IDE中实现我的第一个API(我选择了Chuck Norris API)。 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. 到目前为止,我能够在控制台中显示URL的内容,但在浏览器中却无法显示,这是我的目标。

I wrote this code but I keep getting the same Error message . 我编写了这段代码,但始终收到相同的错误消息

So I need help to successfully implement the API. 因此,我需要帮助才能成功实现API。

The "require" function purpose is to import modules (like the https one when you do require('https') ). 该“规定”功能,目的是导入模块 (如HTTPS之一,当你require('https')

Your error message means that "require" expected the argument to be a node module (not an url). 您的错误消息表示“ require”期望参数为节点模块(而不是url)。

To fetch an url content you can use the " request " module (witch is simpler to use that the native one ): 要获取url内容,可以使用“ request ”模块(witch使用本模块更简单):

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
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM