nodejs获取和返回数据

1、nodeJs

let http = require('http');
let url = require('url');
let fs = require('fs');
let querystring=require('querystring');//操作参数模块

let str='{"id":"1",name:"zhangSan",age:30,sex:"men"}';

function onRequest(request, response){
  let urlStr = url.parse(request.url);
  let param=querystring.parse(urlStr.query);
  console.log("收到请求.");
  response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});//可以解决跨域的请求
  console.log(param);  //输出  { name: '鲁班大师', iq: '250' }
  //str=fs.readFileSync('json.txt');//读取文件内容
  response.write(str);
  response.end();
}
http.createServer(onRequest).listen(8888);

2、html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>获取nodeJs数据</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script>
    $.ajax({
      url: "http://127.0.0.1:8888/",
      type: "GET",
      data:{name:'鲁班大师',iq:'250'},
      contextType: "application/json",
      success: function (res) {
        console.log(eval('('+res+')'))
      },
      error: function (err) {
      }
    });
  </script>
</head>
<body>
</body>
</html>

 

posted @ 2019-03-27 14:47  (⊙o⊙)买噶  阅读(9004)  评论(0编辑  收藏  举报