我已经创建了一个服务器端路由(使用 iron-router)。代码如下:
Router.route( "/apiCall/:username", function(){
var id = this.params.username;
},{ where: "server" } )
.post( function(req, res) {
// If a POST request is made, create the user's profile.
//check for legit request
console.log('post detected')
var userId = Meteor.users.findOne({username : id})._id;
})
.delete( function() {
// If a DELETE request is made, delete the user's profile.
});
这个应用程序在我本地的 3000 端口上运行。现在我已经创建了另一个在端口 5000 上运行的虚拟应用程序。从虚拟应用程序开始,我发出了一个 http.post 请求,然后在应用程序的 3000 端口上监听它。我使用以下代码通过虚拟应用程序触发 http.post 请求:
apiTest : function(){
console.log('apiTest called')
HTTP.post("http://192.168.1.5:3000/apiCall/testUser", {
data: [
{
"name" : "test"
}
]
}, function (err, res) {
if(!err)
console.log("succesfully posted"); // 4
else
console.log('err',err)
});
return true;
}
但我在回调中收到以下错误:
err { [Error: socket hang up] code: 'ECONNRESET' }
无法弄清楚这里的问题是什么。 服务器端路由调用成功,但是没有进入.post()方法。 使用 meteor 版本 1.6 192.168.1.5 是我的 ip 地址
最佳答案
好的,如果我使用 Router.map 函数,问题就解决了。
Router.map(function () {
this.route("apiRoute", {path: "/apiCall/:username",
where: "server",
action: function(){
// console.log('------------------------------');
// console.log('apiRoute');
// console.log((this.params));
// console.log(this.request.body);
var id = this.params.username;
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
if (this.request.method == 'POST') {
// console.log('POST');
var user = Meteor.users.findOne({username : id});
// console.log(user)
if(!user){
return 'no user found'
}
else{
var userId = user._id;
}
}
});
});
关于http - 同一台机器上的 Meteor HTTP.POST 调用(用于测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47568586/