先看题干效果
在这里我们建了一个表单
填入表单需要提交的信息
对两个参数进行获取和一个加法计算
表单html代码
<form action='http://localhost:8080' method="get"> 用户名:<input type="text" name="username"> <br> 密 码:<input type="text" name="password"> <br> <input type='submit' name='submit'> </form>
NodeJS文件
var http = require('http'); var url = require('url'); var fs = require('fs'); http.createServer(function(request,response){ //获取get请求中的参数 var requset_url = request.url; //将字符串格式参数转化为对象使用 var strurl = url.parse(requset_url,true).query var sum = Number(strurl.username)+Number(strurl.password) console.log(sum); //下面这个对象是buffer类型的对象 var content = fs.readFileSync('homework.html') //现在我们要将他转换为字符串类型的对象 content= content.toString().replace('{{sum}}',sum); console.log(content) response.end(content) }).listen(8080,function(){ console.log('服务启动!!!') })
返回的页面
<body> <h3> uesrname+userkeyword={{sum}} </h3> </body>
运行环境
思路:
// 从index.html网页中的action地址设为 本机服务器的地址 localhost:8080
// 然后从get请求中使用url模块来获取请求路径中的参数
// 将字符串格式的参数通过parse方法转换为对象使用
// 使用number强转 计算两个参数的值
// 打包另外一个网页的{{sum}}和整个html内容 默认为buffer类型的对象 转换为字符串
// 最后将{{sum}}用两个参数的值sum替换