简体   繁体   English

如何从Express.js发布到api

[英]How to post to api from Express.js

I am new to Node/Express and to API's in general. 我是Node / Express和API的新手。 Long story short, I am a front end guy diving into backend and architecture for the first time. 长话短说,我是一个前端专家,第一次涉足后端和架构。 The breakdown of my problem is as follows: 我的问题的细分如下:

App description: A web app that allows users to view medical data records. 应用程序描述:一个网络应用程序,允许用户查看医疗数据记录。

Desired feature: Change the state of a json record on page load. 所需功能:更改页面加载时json记录的状态。 When a user opens a record(page), I want to change a json object from UNDIAGNOSED to DIAGNOSED automatically. 当用户打开记​​录(页面)时,我想将json对象从UNDIAGNOSED自动更改为DIAGNOSED。 This needs to be done server side to avoid exposing the api endpoint, which needs to stay hidden for security reasons. 这需要在服务器端完成,以避免暴露api端点,出于安全原因,该端点必须保持隐藏状态。 Think of it like a 'read/unread' email. 将其视为“已读/未读”电子邮件。 Once it has been opened, it changes the state to 'read' 一旦打开,它将状态更改为“已读”

Probelem: ...I am a newb... 皮勒姆:...我是新手...

//When the server GETs a request to this URL
router.get('/content/:contentid', function(req, res, next) {

// Configure the REST platform call
var platform_options = {
    resource: '/content/' + req.params.contentid,
    method: 'POST',
    json: "diagnosis_state: DIAGNOSED"
};

// Make the call
var platform = ihplatform(_config, req.session, platform_options, callback);
platform.execute();

// Result processing
function callback(error, response, body) {
    console.log(response.body);
}

});

I am using a custom HTTP API that was built in-house by another developer. 我正在使用由另一个开发人员内部构建的自定义HTTP API。 The endpoint for the call is dynamically generated via the re.params.contentid. 呼叫的端点是通过re.params.contentid动态生成的。 You will also notice that the call itself is built into the platform.execute function. 您还将注意到调用本身内置在platform.execute函数中。

There is a bit of copy/pasting going on, as I am trying to modify a working call. 我正在尝试修改一个正常工作的呼叫,因此有一些复制/粘贴操作。

My question is this: How do I make an api POST call to a remote API upon the HTTP request for a certain url via express.js? 我的问题是:我如何通过express.js通过HTTP请求某个URL来对远程API进行api POST调用?

Here is what you can do on express.js - 这是您可以在express.js上执行的操作-

1) write a module for route mappings in a separate js file where all the mappings can be listed. 1)在一个单独的js文件中编写用于路由映射的模块,其中可以列出所有映射。 Below is the code snippet of the module file 以下是模块文件的代码片段

 function mappings(app) { var email = require('./routes/emails');// ./routes/emails is js file location exporting UpdateEmail variable which contains function for update app.put('/email/update', email.UpdateEmail); // mapping url /email/update to exported variable UpdateEmail } 

2) add following statement in app.js file where mapRoutes is a .js file created in step 1 2)在app.js文件中添加以下语句,其中mapRoutes是在步骤1中创建的.js文件

 require('./mapRoutes').mappings(app); 

3) Below is the sample app.js file 3)以下是示例app.js文件

 var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Credentials', false); res.header('Access-Control-Max-Age', '86400'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); next(); }); app.options('*', function(req, res) { res.send(200); }); require('./mapRoutes').mappings(app); /// catch 404 and forwarding to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app; 

4) live website running on above code - kidslaughs.com 4)在上述代码上运行的实时网站-kidslaughs.com

I'm not quite sure your question here, because "POSTing from ExpressJS" could mean two different things. 我不太确定您在这里提出的问题,因为“从ExpressJS进行发布”可能意味着两件事。

In the most common case, you are making a POST request from a web page. 在最常见的情况下,您是从网页发出POST请求。 While this might be served or even rendered via Express, the call is originating from the web page. 尽管这可能是通过Express提供或什至通过Express呈现的,但呼叫是从网页发起的。 In that case the javascript on the web page is making the post. 在这种情况下,网页上的javascript就会发布该帖子。 Common web frameworks for that might be jQuery's $.ajax or Angular's $http . 通用的Web框架可能是jQuery的$.ajaxAngular的$http Whatever framework you use, you'll define the data to post, the API endpoint to post to, and what to do with the response. 无论使用哪种框架,都将定义要发布的数据,要发布到的API端点以及如何处理响应。

Another meaning of your question might be that you want your Express app to make a http request from the server side. 您的问题的另一个含义可能是您希望Express应用程序从服务器端发出http请求。 You will need a package to do so, so that you can make a HTTP programatically. 您将需要一个软件包来这样做,以便可以以编程方式创建HTTP。 A popular package for this is request . 一个受欢迎的包装是request

It's hard to say more without knowing what frameworks you are working with. 在不知道您正在使用什么框架的情况下很难说更多。 Keep searching around, you'll figure it out! 不断搜索,您会发现!

I think you're looking for request.js. 我认为您正在寻找request.js。

var request = require('request');
request.post('/content/' + req.params.contentid').form({json: "diagnosis_state: DIAGNOSED"})

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

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