2016-11-14 75 views
0

构建在http,https之上的Nodejs请求库。所以我尝试从请求对象执行nodejs服务器,它说不是请求的一部分。如何执行nodejs请求模块?

那么如何在express下执行或调用下面的代码?

var express = require('express'); 
var app = express(); 
//Load the request module 
var request = require('request'); 

//Lets configure and request 
app.request({ 
    url: 'https://modulus.io/contact/demo', //URL to hit 
    qs: {from: 'blog example', time: +new Date()}, //Query string data 
    method: 'POST', 
    //Lets post the following key/values as form 
    json: { 
     field1: 'data', 
     field2: 'data' 
    } 
}, function(error, response, body){ 
    if(error) { 
     console.log(error); 
    } else { 
     console.log(response.statusCode, body); 
    } 
}); 
app.listen(8080); 
+0

我不明白你在想什么 – tommybananas

+0

这没什么意义。 Express的要点是运行HTTP服务器。尽管可以在运行Express时从节点发出HTTP请求,但通常只能在处理路由的函数中这样做。即浏览器向Express发出请求,然后Express向其他服务器发出请求,从中获取响应,然后使用该响应中的数据确定如何响应第一个请求。你的代码试图在启动时发送一个请求,而不是在资源中发送一个被命中的路由。你甚至没有任何路线。 – Quentin

+0

此外,虽然Express有请求对象,但它们会描述传入的请求。如果你想创建一个传出请求,你需要“需要”一个合适的模块。 – Quentin

回答

2

那是因为你使用app.request,而你应该只使用request,这是指向模块本身的变量。所以你的代码应该是:

var express = require('express'); 
var app = express(); 
//Load the request module 
var request = require('request'); 

//Lets configure and request 
request({ 
     url: 'https://modulus.io/contact/demo', //URL to hit 
     qs: {from: 'blog example', time: +new Date()}, //Query string data 
     method: 'POST', 
     //Lets post the following key/values as form 
     json: { 
      field1: 'data', 
      field2: 'data' 
     } 
    }, function(error, response, body){ 
     if(error) { 
      console.log(error); 
     } else { 
      console.log(response.statusCode, body); 
     } 
    }); 
app.listen(8080); 
相关问题