Blogger Information
Blog 77
fans 0
comment 2
visits 56000
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
请求与响应
南瓜又个梦
Original
680 people have browsed it


如何发送请求
1,用Chrome地址栏
2.用curl命令(curl是一个没有界面的浏览器)
帮助我发送请求的叫做用户代理,英文名字叫User Agent

这是一张在Chrome上看请求的图,注意在红点下方那个输入框内不要有出了filter的任何东西,不然会导致header,previw,等显示不出来。

如何做出一个响应
响应代码是放在服务器上的,每被请求一次就会执行一次。

以下是服务器上的一个简单的代码

  1. var http = require('http')
  2. var fs = require('fs')
  3. var url = require('url')
  4. var port = process.argv[2]
  5. if(!port){
  6. console.log('请指定端口号好不啦?\nnode server.js 8888 这样不会吗?')
  7. process.exit(1)
  8. }
  9. var server = http.createServer(function(request, response){
  10. var parsedUrl = url.parse(request.url, true)
  11. var pathWithQuery = request.url
  12. var queryString = ''
  13. if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  14. var path = parsedUrl.pathname
  15. var query = parsedUrl.query
  16. var method = request.method
  17. /******** 从这里开始看,上面不要看 ************/
  18. console.log('有个傻子发请求过来啦!路径(带查询参数)为:' + pathWithQuery)
  19. if(path === '/'){
  20. response.statusCode = 200
  21. response.setHeader('Content-Type', 'text/html;charset=utf-8')
  22. response.write(`二哈`)
  23. response.end()
  24. } else if(path === '/x'){
  25. response.statusCode = 200
  26. response.setHeader('Content-Type', 'text/css;charset=utf-8')
  27. response.write(`body{color: red;}`)
  28. response.end()
  29. } else {
  30. response.statusCode = 404
  31. response.setHeader('Content-Type', 'text/html;charset=utf-8')
  32. response.write(`你输入的路径不存在对应的内容`)
  33. response.end()
  34. }
  35. /******** 代码结束,下面不要看 ************/
  36. })
  37. server.listen(port)
  38. console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)

这是代码全部的解释
https://www.yuque.com/ninesean/newbie/dvgyc9

path :是不带查询参数的路径
query :是查询参数的对象参数的形式{a:’1’}
queryString:是查询参数字符串的形式?a=1
pathwithQuery:带查询参数的路径
request:是请求对象
response:是响应对象

(1) 数字1旁边的``包裹的内容可以换行和有空格,其他形式的引号换行用/n
(2) 文件的后缀名是让电脑选择打开文件的应用,和文件内容无关,定义文件内容的是content-Type

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post