node.js 如何使用节点 js 将字符串变量作为参数传递给 REST API 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17568280/
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
How to pass string variable as parameter to REST API call using node js
提问by Prem
var express = require('express');
var app = express();
// Get Pricing details from subscription
app.get('/billingv2/resourceUri/:resourceUri', function(req, res) {
var pricingDetail = {}
pricingDetail.resourceUri = req.params.resourceUri;
pricingDetail.chargeAmount = '25.0000';
pricingDetail.chargeAmountUnit = 'per hour';
pricingDetail.currencyCode = 'USD';
res.send(pricingDetail); // send json response
});
app.listen(8080);
I need to call the above API using the string parameter vm/hpcloud/nova/standard.small.
Please note that vm/hpcloud/nova/standard.smallis a single string param.
我需要使用字符串参数调用上述 API vm/hpcloud/nova/standard.small。请注意,这vm/hpcloud/nova/standard.small是一个单一的字符串参数。
回答by Jess
Assuming node.js and express.js.
假设 node.js 和 express.js。
Register a route with your application.
向您的应用程序注册路由。
server.js:
服务器.js:
...
app.get('/myservice/:CustomerId', myservice.queryByCustomer);
....
Implement the service using the req.paramsfor the passed in Id.
使用req.params传入的 ID实现服务。
routes/myservice.js:
路线/myservice.js:
exports.queryByCustomer = function(req, res) {
var queryBy = req.params.CustomerId;
console.log("Get the data for " + queryBy);
// Some sequelize... :)
Data.find({
where : {
"CustomerId" : parseInt(queryBy)
}
}).success(function(data) {
// Force a single returned object into an array.
data = [].concat(data);
console.log("Got the data " + JSON.stringify(data));
res.send(data); // This should maybe be res.json instead...
});
};
回答by DonutMan
On your app.js:
在你的 app.js 上:
url: http://localhost:3000/params?param1=2357257¶m2=5555
var app = express();
app.get('/params', function (req,res) {
// recover parameters
var param1=req.query.param1;
var param2=req.query.param2;
// send params to view index.jade
var params = {
param1: param1,
param2: param2
};
res.render('index.jade', {parametros: parametros});
});
At index.jade to recover values:
在 index.jade 恢复值:
p= params.param1
p= params.param2
回答by Prêtre Thierry
encode your url passed as parameter :
对作为参数传递的 url 进行编码:
vm%2Fhpcloud%2Fnova%2Fstandard.small
vm%2Fhpcloud%2Fnova%2Fstandard.small
Used site : http://meyerweb.com/eric/tools/dencoder/
回答by Manuel van Rijn
you're probably searching for this: http://expressjs.com/api.html#res.json
你可能正在寻找这个:http: //expressjs.com/api.html#res.json
so it would be
所以它会
res.json(pricingDetail);
回答by Jules Goullee
Not use string, if you need to get this use and id or readable string, '/path/my-article' not '/path/my article'
不使用字符串,如果你需要得到这个使用和 id 或可读的字符串,'/path/my-article' 不是 '/path/my article'

