Javascript 使用Node';在Browserify中完全使用http模块
我想在Chrome等普通浏览器中运行以下Node.js代码:Javascript 使用Node';在Browserify中完全使用http模块,javascript,node.js,browserify,Javascript,Node.js,Browserify,我想在Chrome等普通浏览器中运行以下Node.js代码: var http = require('http') var assert = require('assert') http.createServer((req, res) => { // Send hello greetings for all clients. res.writeHead(200, { 'Content-Type': 'text/html' }) res.end('<h1>
var http = require('http')
var assert = require('assert')
http.createServer((req, res) => {
// Send hello greetings for all clients.
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end('<h1>Hello, world!</h1>')
}).listen(3000, () => {
// Get the response myself.
http.request({
hostname: 'localhost',
port: 3000,
path: '/',
method: 'GET'
}, res => {
assert.equals(res.statusCode, 200)
// Get the chunked content of the response.
res.setEncoding('utf8')
var content = ''
res.on('data', (chunk) => {
content += chunk
})
res.on('end', () => {
// Finish to get the chunked.
assert.equals(content, '<h1>Hello, world!</h1>')
})
})
})
var http=require('http'))
var assert=require('assert')
http.createServer((req,res)=>{
//向所有客户发送问候。
res.writeHead(200,{'Content-Type':'text/html'})
res.end('你好,世界!')
}).听(3000,()=>{
//我自己得到答复。
http.request({
主机名:“localhost”,
港口:3000,
路径:“/”,
方法:“获取”
},res=>{
assert.equals(res.statusCode,200)
//获取响应的分块内容。
res.setEncoding('utf8')
变量内容=“”
res.on('数据',(块)=>{
内容+=块
})
res.on('结束',()=>{
//完成以得到块。
assert.equals(内容为“你好,世界!”)
})
})
})
当代码在浏览器上正确运行时,将传递两个断言,而不会出现任何错误
它需要与浏览器兼容的require(…)
函数才能在浏览器中运行节点代码。
我找到了一个合适的库,但是有很多Node.js
不幸的是,我不能使用http.createServer(…)
和http.listen(…)
函数
如何在浏览器上正确运行节点代码
添加:
它不要求http.createServer(…)没有托管新服务器,只需模拟即可http.request(…)
和http.listen(…)
是相同的
我认为可以使用mock object进行模拟。可能是@Sargo Darya的复制品。我在问题中添加了一些补充。我知道可能是@Sargo Darya的复制品。我在问题中加了一些补充。