nodejs httpserver

寻技术 JS脚本 / Node.Js 2023年07月11日 114

用nodejs服务器去拿取后台的数据。(我刚开始学的nodejs的时候是一个蒙圈的宝宝 t.t,开始接触的时候,在本地搭建去拿数据。之前菜鸟的我都不知道路由是神马[囧囧])。

--> index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/get_data"] = requestHandlers.get_data;
server.start(router.route, handle);

--> server.js

var http = require("http");
var url = require("url");
function start(route, handle) {
  function onRequest(request, response) {
    var postData = "";
    var pathname = url.parse(request.url).pathname;
    var getData  = url.parse(request.url).query;
    console.log("Request for " + pathname + " received.");
    request.setEncoding("utf8");
    request.addListener("data", function(postDataChunk) {
      postData += postDataChunk;
      console.log("Received POST data chunk '"+ postDataChunk + "'.");
    });
    request.addListener("end", function() {
      if(postData == ""){
           postData = getData;
      }
      route(handle, pathname, response, postData);
    });
  }
  http.createServer(onRequest).listen(8888);//当你成功滴时候,你的数据在这里。
  console.log("Server has started.");
}
exports.start = start;

 

--> router.js

function route(handle, pathname, response, postData) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response, postData);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}
exports.route = route;

--> requestHandlers.js

var querystring = require("querystring");
var request = require('request');//请求模块
//get data
function get_data(res, postData) {
        console.log('get debug post data',JSON.stringify(postData));
        request.post({
                        url : 'xxx.xx.xxx',//你请求后台的链接
                        form : {
                              //params,你的请求的参数
                        }
                }, function(error, response, body) {
                        console.log('body is',body);
                        res.writeHead(200,{'Content-Type':'application/json; charset=utf8', 'Access-Control-Allow-Origin':'*', 'Accept-Language':'zh-CN'});//响应头
                        res.end(body);
                });
}
exports.get_data = get_data;

然后,你可以启动你的服务:node index,当命令行出现  “Server has started”。如果出现什么错误的话,可能的情况是你的node_modules里的模块没有安装完成,按照缺少的安装就好了。对了,还有一个package.json,通过 npm init去生成。npm install xxx --dev去安装相应的包。然后去你的浏览器输入 127.0.0.1:8888/get_data,看有没有你想要的数据哦。


 
                    
            
                
关闭

用微信“扫一扫”