您当前的位置: 首页 > 

qq_34412985

暂无认证

  • 0浏览

    0关注

    1061博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

node发送响应

qq_34412985 发布时间:2018-12-22 17:17:18 ,浏览量:0

var http = require('http'); var server=http.createServer(); server.on('request',function(request,response){

console.log('收到客户端的请求了,请求路径是:'+request.url)

//response对象有一个方法:write可以用来给客户端发送响应数据

//write可以使用多次,但是最后一定要使用end来结束响应,否则客户端会一直等待

response.write('hello')

response.write('nodejs')

//告诉客户端,我的话说完了,你可以呈递给用户了

var url = request.url; if(url=='/products'){     var products = [     {       name:'苹果x',       price:8888     },     {       name:'菠萝',       price:888     },           {       name:'小辣椒',       price:1999     }     ]

//浏览器不知道服务器响应内容的编码的情况下会按照当前操作系统的默认编码去解析,中文操作系统默认是gbk

response.setHeader('Content-Type','text/plain;charset=utf-8')     //响应内容只能是二进制数据或者字符串     response.end(products)

}) server.listen(3000,function(){

console.log('服务器启动成功了,可以通过http://127.0.0.1;3000/来进行访问')

})

//响应内容只能是二进制数据或者字符串,否则会报错:JSON.stringify(products)     JSON.parse('products')报错

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type strin g or Buffer. Received type object

 

关注
打赏
1653291990
查看更多评论
立即登录/注册

微信扫码登录

0.0391s