用nodejs搭建服务器
- 安装nodejs ,搭建nodejs环境

- 自己新建一个文件夹
node_form
,用于存放此处实验的代码;此文件里面新建index.js
文件;并且在此文件夹中打开命令行,输入以下命令,初始化项目。
npm init-y
var http=require('http')var fs=require('fs')var url=require('url')var server= http.createServer()
server.on('request',function(req,res){var parseObj= url.parse(req.url,true)var pathname= parseObj.pathnameif(pathname==='/'){
fs.readFile('./index.html',function(err,data){if(err){
console.log('false')
res.end('false')}else{
console.log('true')
res.setHeader('Content-Type','text/html;charset=utf-8')
res.end(data)}})}elseif(pathname==='/form'){var Obj= parseObj.query
console.log(Obj)}})
server.listen(4000,function(){
console.log('server success,http://localhost:4000/')})
运行服务器
- 在
node_form
文件里面新建index.html
文件。 - 在
index.html
写入以下代码
<!DOCTYPE html><html><head><metacharset='utf-8'><title>Web</title></head><body><formaction="/form"method="GET"><inputname="input"type="text"value=""id=""/><br/><textareaname="textarea"id=""cols="22"rows="10"></textarea><button> 按钮</button></form></body></html>
node index.js
- 最后在html中输入,然后点击
按钮
,即可在命令窗口看到自己所输入的数据对象
项目结构如下:
|--- node_form //文件夹
| |--- index.html //网页
| |--- index.js //主文件
| |--- package.json