问题描述
我对Node.js很新。我正在尝试使用NodeJS调用服务。如果可以指出以下代码的NodeJS等价物将会有所帮助:
$。ajax({
类型: POST,
url:/ WebServiceUtility.aspx/CustomOrderService,
data:{'id':'2'},
contentType:application / json; charset = utf-8,
dataType:json,
成功:函数(消息){
ShowPopup(消息);
}
});
任何有用的链接都将非常受欢迎。
var http = require('http');
var data = JSON.stringify({
'id':'2'
});
var options = {
host:'host.com',
port:'80',
path:'/ WebServiceUtility.aspx/CustomOrderService',
方法:'POST',
header:{
'Content-Type':'application / json; charset = utf-8',
'Content-Length':data.length
}
};
var req = http.request(options,function(res){
var msg ='';
res.setEncoding('utf8');
res.on('data',function(chunk){
msg + = chunk;
});
res.on('end',function(){
console.log(JSON.parse(msg));
});
});
req.write(data);
req.end();
此示例创建数据有效负载,即JSON。然后它设置HTTP post选项,例如主机,端口,路径,标题等。然后设置请求本身,我们收集解析响应。然后我们将POST数据写入请求本身,并结束请求。
I'm quite new to Node.js. I was experimenting with how to call a service using NodeJS. Would be helpful if could point out the NodeJS equivalent of the code below:
$.ajax({
type: "POST",
url: "/WebServiceUtility.aspx/CustomOrderService",
data: "{'id': '2'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (message) {
ShowPopup(message);
}
});
Any helpful links would be most appreciated.
The Node.js equivalent to that code can be using jQuery server-side, using other modules, or using the native HTTP/HTTPS modules. This is how a POST request is done:
var http = require('http');
var data = JSON.stringify({
'id': '2'
});
var options = {
host: 'host.com',
port: '80',
path: '/WebServiceUtility.aspx/CustomOrderService',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': data.length
}
};
var req = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
console.log(JSON.parse(msg));
});
});
req.write(data);
req.end();
This example creates the data payload, which is JSON. It then sets up the HTTP post options, such as host, port, path, headers, etc. The request itself is then set up, which we collect the response for parsing. Then we write the POST data to the request itself, and end the request.
这篇关于使用nodejs调用Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!