Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nodejs搭建简单服务器 #17

Open
hezizi opened this issue Sep 23, 2018 · 0 comments
Open

nodejs搭建简单服务器 #17

hezizi opened this issue Sep 23, 2018 · 0 comments

Comments

@hezizi
Copy link
Owner

hezizi commented Sep 23, 2018

nodejs文档

创建一个简单的http服务器:

  • 加载http模块
  • 创建http服务对象
  • 监听用户请求事件
  • 设置监听端口

新建一个demo.js文件

  1. 加载http模块
    const http = require('http');
  1. 创建http服务对象

http.createServer()方法创建http服务对象

    const server = http.createServer();
  1. 监听用户请求事件并设置监听端口

response.write(chunk[, encoding][, callback])
通过res.write()方法发送响应体,可多次调用
有三个参数,第一个参数必传,必须为字符串或buffer,不能为数组,对象等
第二,三个参数选传,分别为编码格式,默认为utf8,另外是回调

必须调用res.end()方法告诉服务器响应完毕,可结束响应

    server.on('request', (req, res) => {
      // 设置请求头
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.write('hello node');
      res.end();
    }).listen(8888, () => {
      console.log('服务已经启动');
    })

进一步优化代码:

    const http = require('http');
    http.createServer((req, res) => {
      // 设置请求头
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.end('hello node');
    }).listen(8888, () => {
      console.log('服务已经启动');
    })

到此一个最简单的http服务器就搭建完成,命令行运行node demo,在浏览器中输入localhost:8888就可以看到hello node。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant