[英]How to do a Web Server in NodeJs that makes a REST call to API REST?
我做了很多研究,但找不到解決方案。
我必須在Node.js中做一個Web服務器,直到這里,好...但是如何進行REST調用? 是否必須使用快遞? 我只是不明白。 我發現了很多東西,但我不知道如何使用它們。 我必須對API REST進行REST調用。
例如:我的Web服務器啟動(在本地主機上),它允許在Facebook上共享某些內容。
但是我什至不知道將API代碼放在哪里。
謝謝! 附言:我不是英語,所以我無法很好地表達自己
這是Web服務器代碼:
var http = require('http');
var server = http.createServer(function (req, res) {
res.end('Web Server');
})
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
我知道這很容易,但我不明白...
要指定, 分配是“實現一個nodejs服務器,該服務器能夠對http://www.programmableweb.com/中的任何REST API提供進行REST調用並顯示結果”。
REST API只能使用節點本機庫進行開發。 在下面的示例中,我有用戶url API開發
var http = require('http');
var url = require('url');
var server = http.createServer(function (req, res) {
var path = url.parse(req.url, true);
console.log(path.pathname);
if(path.pathname == '/customer'){
// Send some Customer Data
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
customerName : 'abc',
purchase : 200,
deliverDate : new Date()
}));
}else if(path.pathname == '/vendor'){
// Send some Customer Data
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
vendorName : 'abc',
price : 1000,
orderDate : new Date()
}));
}else{
res.end('Wrong Path !!! - API not Found ');
}
})
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
還有其他方法,例如使用快速中間件來避免手動進行URL解析。
var express = require('express');
var app = express();
app.get('/customer', function(req, res) {
res.send({
customerName : 'abc',
purchase : 200,
deliverDate : new Date()
});
});
app.get('/vendor', function(req, res) {
res.send({
vendorName : 'abc',
price : 1000,
orderDate : new Date()
});
});
app.listen(1337);
console.log('Listening on port 1337...');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.