想要一个将Json POST到某个远程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;
---使用Node自己的http.request()
- 文件routes/nodehttp.js
---
---当你只想发布一些Json数据时,通过改为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;
也许是最简单的
---使用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;
享受&我希望这些更全面的演示能够帮助你。
答案 0 :(得分:-1)
看起来不错。记录不同的选项需要相当多的努力。
稍后我会添加一个Requestify.js示例。请继续关注并在上面查找