node浏览器调试
node --inspect --inspect-brk app.js
- 打开chrome浏览器,输入chrome://inspect进行调试
node进程管理工具
- supervisor
- nodemon
- forever
- pm2
response
- 若不设置response的头信息,浏览器默认以html形式解析字符串
- writeHead
- 第一个参数为状态码
- 第二个参数用来设置头部具体信息,例如,content-type
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'content-type': 'text/plain'
})
res.write('<div>hello world</div>')
res.end();
});
server.listen('7002');
http.request
将http.request请求封装成模块
cors
- 当请求的协议、域名或者端口号与当前浏览器客户端地址不同时,会产生跨域限制,这是浏览器本身的安全策略。可以通过在服务端设置 ‘Access-Control-Allow-Origin’: ‘*’ 来解决。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>04-cors</title>
</head>
<body>
<script>
const xhr=new XMLHttpRequest();
xhr.open('get','http://localhost:3000/api/data?a=3',true);
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
console.log(xhr.responseText);
}else{
throw new Error('请求过程中发生错误');
}
}else{
console.log('---');
}
}
xhr.send();
</script>
</body>
</html>
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const urlObj = url.parse(req.url);
switch (urlObj.pathname) {
case '/api/data':
res.writeHead(200, {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.write("{a:2,b:3}");
break;
default:
res.write('hello world');
}
res.end();
});
server.listen(3000, () => {
console.log('http://localhost:3000');
});