想要一个节点路由器,将POST Json发送到某些远程API?从节点的托管路由器发布到远程API(不是托管节点的API)
今天早上我为这个问题付出了很多努力,所以我想通过提供一些综合例子来分享这个好处。
在每个例子中,路由器都有一个GET方法,当被调用时,POSTS回到同一个路由器。我也非常清楚地展示了如何发送以及如何访问接收到的数据。
在Node.js中,在路由器中,您有时可能需要从路由器发送到某个远程API。
---使用--- npm install needle -save
文件routes/nee.js
---
var express = require('express');
var router = express.Router();
var needle = require('needle');
router.get('/', function (req, resp) {
var dat = { theGreatest: 'ChuckBerry' };
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
needle.post(lookbackURL, dat, { json: true });
resp.redirect('/');
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
---使用--- npm install request -save
文件routes/req.js
---
var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function (req, resp) {
var dat = { theGreatest: 'ChuckBerry' };
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
request.post(lookbackURL, { json: dat });
resp.redirect('/');
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
---使用节点的自己的http.request()
- 文件routes/nodehttp.js
---
---当你只想发布一些Json数据使y我们的生活变得更加简单的,而不是做的content-type=application/json
-----
var express = require('express');
var router = express.Router();
var http = require('http');
router.get('/', function (req, resp) {
var hst = req.headers.host.split(':');
var dat = { theGreatest: 'ChuckBerry' };
var bdy = JSON.stringify(dat); // you have to take care of this for yourself
var options = { host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT' //PUT!
, headers: { 'Content-Type': 'application/json' }
};
var r = http.request(options);
r.write(bdy);
r.end();
resp.sendStatus(200);
});
router.put('/', function (req, resp) { // PUT. it's a PUT not a POST
console.log('body[\'theGreatest\']', req.body['theGreatest']); // But here you DON'T have to parse it for yourself.
//^I'm happy for that even if I am feeling the loss of symmetry.
// ^^ At the same this is why your life is easier in a PUT instead of a POST.
resp.sendStatus(200);
});
module.exports = router;
一个PUT也许最简单的所有
---使用--- npm install requestify -save
文件routes/rify.js
---
var express = require('express');
var router = express.Router();
var requestify = require('requestify');
router.get('/', function (req, resp) {
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
requestify.post(lookbackURL, {
theGreatest: 'ChuckBerry'
})
.then(function (res) {
//res.getBody(); // JSON parsed or XML object
//res.body; // or get the raw
res.redirect('/');
});
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
享受&我希望这些更全面的演示也能帮助你。
这些都不符合[help] – charlietfl
中概述的本网站的问题/答案格式结构您很想分享知识,但这不是恰当的地方。 –
虽然我同意这个网站上有很多资料需要这种关注,清晰度和帮助 – Steve