NodeJS 中的 Http

缺乏、安全感 2022-05-28 10:50 250阅读 0赞

简单的创建一个 HttpServer

  1. http.createServer(function (request, response){
  2. response.writeHead(200, { 'Content-Type': 'text/plain'});
  3. response.write("Hello World");
  4. response.end();
  5. }).listen(8080, '127.0.0.1');
  6. console.log('Server running on port 8080.');

右键运行这个JS代码,可以看到’Server running on port 8080.’的Log信息,表示创建成功。
在browser的URL中输入localhost:8080 来测试,页面上返回Hello World

可以自己创建一个server读取一些数据,比如读取一个文件:

  1. var http = require('http');
  2. var fs = require('fs');
  3. http.createServer(function (request, response){
  4. fs.readFile('data.txt', function readData(err, data) {
  5. response.writeHead(200, { 'Content-Type': 'text/plain'});
  6. response.end(data);
  7. });
  8. // 或者
  9. //fs.createReadStream(`${__dirname}/index.html`).pipe(response);
  10. }).listen(8080, '127.0.0.1');
  11. console.log('Server running on port 8080.');

在browser的URL中输入localhost:8080 来测试,页面上返回data.txt中的信息

可以获取request中的url,可以用来实现rest风格的请求:

  1. //server.js
  2. //var url = require('url');
  3. http.createServer(function(req, res) {
  4. //var pathname = url.parse(req.url).pathname;
  5. //console.log(pathname)
  6. // 主页
  7. if (req.url == "/") {
  8. res.writeHead(200, { "Content-Type": "text/html" });
  9. res.end("Welcome to the homepage!");
  10. }
  11. // About页面
  12. else if (req.url == "/about") {
  13. res.writeHead(200, { "Content-Type": "text/html" });
  14. res.end("Welcome to the about page!");
  15. }
  16. // 404错误
  17. else {
  18. res.writeHead(404, { "Content-Type": "text/plain" });
  19. res.end("404 error! File not found.");
  20. }
  21. }).listen(8080, "localhost");
  22. console.log('Server running on port 8080.');

在browser的URL中输入http://localhost:8080/about 来测试,页面上返回Welcome to the about page!

除开了在Browser中的url中直接来验证外,还可以自己手动在 js 中发送请求来测试上面写的 server 是否已经正常运行:

  1. //client.js
  2. var http = require('http');
  3. return http.get({ //发送一个 get 请求,但是没有post请求的简写
  4. //host: 'localhost',
  5. //hostname: "",
  6. port: 8080,
  7. path: '/about'
  8. }, function(response) {
  9. var body = '';
  10. response.on('data', function(d) {
  11. body += d;
  12. });
  13. response.on('end', function() {
  14. console.log(body); //Welcome to the about page!
  15. //var parsed = JSON.parse(body);
  16. // callback({
  17. // email: parsed.email,
  18. // password: parsed.pass
  19. // });
  20. });
  21. });

request方法用于发出HTTP请求,它的使用格式如下。
http.request(options[, callback])

request方法的options参数,可以是一个对象,也可以是一个字符串。如果是字符串,就表示这是一个URL,Node内部就会自动调用url.parse(),处理这个参数。

  • options对象可以设置如下属性。
  • host:HTTP请求所发往的域名或者IP地址,默认是localhost。
  • hostname:该属性会被url.parse()解析,优先级高于host。
  • port:远程服务器的端口,默认是80。
  • localAddress:本地网络接口。
  • socketPath:Unix网络套接字,格式为host:port或者socketPath。
  • method:指定HTTP请求的方法,格式为字符串,默认为GET。
  • path:指定HTTP请求的路径,默认为根路径(/)。可以在这个属性里面,指定查询字符串,比如/index.html?page=12。如果这个属性里面包含非法字符(比如空格),就会抛出一个错误。
  • headers:一个对象,包含了HTTP请求的头信息。
  • auth:一个代表HTTP基本认证的字符串user:password。
  • agent:控制缓存行为,如果HTTP请求使用了agent,则HTTP请求默认为Connection: keep-alive,它的可能值如下:
  • undefined(默认):对当前host和port,使用全局Agent。
  • Agent:一个对象,会传入agent属性。
  • false:不缓存连接,默认HTTP请求为Connection: close。
  • keepAlive:一个布尔值,表示是否保留socket供未来其他请求使用,默认等于false。
  • keepAliveMsecs:一个整数,当使用KeepAlive的时候,设置多久发送一个TCP KeepAlive包,使得连接不要被关闭。默认等于1000,只有keepAlive设为true的时候,该设置才有意义。

    // server.js

    //当客户端采用POST方法发送数据时,服务器端可以对data和end两个事件,设立监听函数。
    var http = require(‘http’);
    http.createServer(function (req, res) {

    1. var content = "";
    2. req.on('data', function (chunk) {
    3. content += chunk;
    4. });
    5. req.on('end', function () {
    6. res.writeHead(200, { "Content-Type": "text/plain"});
    7. res.write("You've sent: " + content);
    8. res.end();
    9. });

    }).listen(8080, ‘localhost’);
    console.log(‘Server running on port 8080.’);

    // client.js

    var http = require(‘http’);

    1. var querystring = require('querystring');
    2. var postData = querystring.stringify({
    3. 'msg' : 'Hello World!'
    4. });
    5. var req = http.request({ //没有Post方法,只能发送原生的request请求
    6. //host: 'http://localhost',
    7. //hostname: "",
    8. port: 8080,
    9. path: '/',
    10. method: "POST",
    11. headers: {
    12. 'Content-Type': 'application/x-www-form-urlencoded',
    13. 'Content-Length': postData.length
    14. }
    15. }, function(response) {
    16. var body = '';
    17. response.on('data', function(d) {
    18. body += d;
    19. });
    20. response.on('end', function() {
    21. console.log(body);//You've sent: msg=Hello%20World!
    22. //var parsed = JSON.parse(body);
    23. // callback({
    24. // email: parsed.email,
    25. // password: parsed.pass
    26. // });
    27. });
    28. });
    29. req.on('error', function(e) {
    30. console.log('problem with request: ' + e.message);
    31. });
    32. // write data to request body
    33. req.write(postData);
    34. req.end();

发表评论

表情:
评论列表 (有 0 条评论,250人围观)

还没有评论,来说两句吧...

相关阅读