javascript 使用 Express.JS 使用 API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34327599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:34:01  来源:igfitidea点击:

Using Express.JS to consume an API

javascriptjsonnode.jsapiexpress

提问by Onion

var express = require('express');
var app = express();
var path = require('path');
var api = require('./api');


app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
})


app.listen(8080)
console.log('Server Running');

I know that we are requiring the express module. We are using the express function, we are requiring the module path and storing the reference in variable path and doing the same with api but beyond that I am a little lost. If I wanted to connect to twitter API how would I go about doing this? Can someone please explain the logic behind it so i can go learn this better and apply it by myself with different API's? I sincerely and greatly appreciate all of your help!

我知道我们需要 express 模块。我们正在使用 express 函数,我们需要模块路径并将引用存储在变量路径中,并使用 api 做同样的事情,但除此之外我有点迷茫。如果我想连接到 twitter API,我将如何去做?有人可以解释一下它背后的逻辑,这样我就可以更好地学习并使用不同的 API 自己应用它吗?我衷心感谢您的帮助!

回答by Yerken

Express is a framework for organising your web application server. You open up certain API's routes to listen on the path and respond to the requests when necessary.

Express 是一个用于组织 Web 应用程序服务器的框架。您打开某些 API 的路由来监听路径并在必要时响应请求。

You can open API's only for internal use, i.e. calls from the browser running your app. Or you can expose your API to outer world (for example twitter API is doing that).

您可以打开 API 仅供内部使用,即从运行您的应用程序的浏览器调用。或者您可以将您的 API 暴露给外部世界(例如 twitter API 正在这样做)。

To connect to twitter API you need to make an outgoing request from your webserver. There are many ways to go about that, starting from native nodeJS package httphttps://nodejs.org/api/http.htmlto much more popular alternative requesthttps://github.com/request/request

要连接到 twitter API,您需要从您的网络服务器发出一个传出请求。有很多方法可以解决这个问题,从原生 nodeJS 包httphttps://nodejs.org/api/http.html到更流行的替代requesthttps://github.com/request/request

One thing to note here is that NodeJS web server are in general less restrictive than other language servers, especially when it comes to organising your app and code architecture. Hence more issues for beginners. Feel free to ask more questions.

这里需要注意的一件事是,NodeJS Web 服务器通常比其他语言服务器的限制要少,尤其是在组织应用程序和代码架构方面。因此,初学者的问题更多。随意提出更多问题。

Main purpose of app in

应用程序的主要目的

var app = express()

is to listen to routes (it is as well used to render pages, adding middleware etc.) and only that.

是监听路由(它也用于渲染页面,添加中间件等),仅此而已。

So assume u have a button on your UI which allows you to connect to twitter API. So on the click you make a GET request to your own server, to /api/twitter/connect. On your server you listen on this path as follows:

所以假设你的 UI 上有一个按钮,允许你连接到 twitter API。因此,在单击时,您向自己的服务器发出 GET 请求,以/api/twitter/connect. 在您的服务器上,您在此路径上侦听如下:

var request = require('request'); //assuming you installed this module
app.get('/api/twitter/connect', function(req, res){
  request(TWITTER_API_URL + API_KEYS, function(err, body){
      res.json(body); //res is the response object, and it passes info back to client side
  });
});

回答by Shawon Kanji

You can use "request" package to send requests. But in case of Cross-Origin-Request you must use "HTTPS" instead of "HTTP". You can configure Your request according to your request type like this..

您可以使用“请求”包来发送请求。但是在跨源请求的情况下,您必须使用“HTTPS”而不是“HTTP”。您可以根据您的请求类型配置您的请求,如下所示..

 //Load the request module
var request = require('request');

//Lets configure and request
request({
    url: 'https://example.com/abc/demo', //URL to hit
    qs: {from: 'example', time: +new Date()}, //Query string data
    method: 'GET', // specify the request type
    headers: { // speciyfy the headers
        'Content-Type': 'MyContentType',
        'Custom-Header': 'Custom Value'
    },
    body: 'Hello Hello! String body!' //Set the body as a string
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
});

Besides this there are others way to do the same. And for twitter you can also checkout the module called "twitter"

除此之外,还有其他方法可以做到这一点。对于 twitter,您还可以查看名为“ twitter”的模块