gpt4 book ai didi

json - 使用 Angular 服务传递 json 数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:13 24 4
gpt4 key购买 nike

我一直在尝试通过 json 请求使用 Angular2 服务将数据发布到 Node API。但是,当我通过 Angular2 服务传递参数时,我的 Node API 接收到 undefined 值。 下面是我的 Angular 服务代码

 enrolldegree(name,depart,enrollnumber,cgpa,university,token){
let peer = '["localhost:10151","localhost:10351"]';
let fcn = 'initDegree';
let argument = '["'+name+'","'+depart+'","'+enrollnumber+'","'+cgpa+'","'+university+']';
let headers = new Headers({'cache-control':'no-cache', 'Content-Type': 'application/json', 'authorization':'Bearer '+token});
let options = new RequestOptions({ headers: headers });
let body1 = new URLSearchParams();
body1.set('peers','["localhost:10151","localhost:10351"]');
body1.set('fcn',fcn);
body1.set('args',argument);
let body = JSON.stringify(body1);
console.log('server logs',body);
return this.http.post('http://localhost:4000/channels/mychannel/chaincodes/mycc', body, options )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error shit bang in'));
}

这是我的 Node API 代码

  app.post('/channels/:channelName/chaincodes/:chaincodeName', function(req, res) {
logger.debug('==================== INVOKE ON CHAINCODE ==================');
var peers = req.body.peers;
var chaincodeName = req.params.chaincodeName;
var channelName = req.params.channelName;
var fcn = req.body.fcn;
var args = req.body.args;
logger.debug('channelName : ' + channelName);
logger.debug('chaincodeName : ' + chaincodeName);
logger.debug('fcn : ' + fcn);
logger.debug('args : ' + args);
if (!peers || peers.length == 0) {
res.json(getErrorMessage('\'peers\''));
return;
}
if (!chaincodeName) {
res.json(getErrorMessage('\'chaincodeName\''));
return;
}
if (!channelName) {
res.json(getErrorMessage('\'channelName\''));
return;
}
if (!fcn) {
res.json(getErrorMessage('\'fcn\''));
return;
}
if (!args) {
res.json(getErrorMessage('\'args\''));
return;
}

invoke.invokeChaincode(peers, channelName, chaincodeName, fcn, args, req.username, req.orgname)
.then(function(message) {
res.send(message);
});
});

当我尝试使用curl查询发布数据时,一切正常。这是我在发出post请求时使用的curl查询

curl -s -X POST \
http://localhost:4000/channels/mychannel/chaincodes/mycc \
-H "authorization: Bearer $ORG1_TOKEN" \
-H "content-type: application/json" \
-d '{
"peers": ["localhost:7051", "localhost:8051"],
"fcn":"initDegree",
"args":["Khurrum","software","Ned11831314","3.5","Ned"]
}'

我在 Angular2 服务中做错了什么?

最佳答案

在您的 Angular 服务代码中,不要将请求正文创建为 URLSearchParams 实例,而是尝试以下操作:

let body1 = {
peers: ["localhost:10151","localhost:10351"],
fcn: fcn,
args: argument
}
let body = JSON.stringify(body1);

关于json - 使用 Angular 服务传递 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com