Node搭建简易服务器 — express
JavaScrip高级教程 · 64 字
- 安装express
npm i express
- 监听GET请求
const url = require("url")
const express = require("express");
const app = express();
const port = 3000;
app.get('/', (req, res) => {
const { query } = url.parse(req.url, true)
console.log('query', query.token);
res.send("hello world")
})
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
- 处理跨域
app.use((req, res, next) => {
//判断路径
if (req.path !== '/' && !req.path.includes('.')) {
res.set({
'Access-Control-Allow-Credentials': true, //允许后端发送cookie
'Access-Control-Allow-Origin': '*', //任意域名都可以访问,或者基于我请求头里面的域
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type', //设置请求头格式和类型
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
'Content-Type': 'application/json; charset=utf-8'//默认与允许的文本格式json和编码格式
})
}
req.method === 'OPTIONS' ? res.status(204).end() : next()
})
- 利用内置模块url处理query参数
const { query } = url.parse(req.url, true)
console.log('query', query.token);
- 服务器热更新
安装nodemon:npm i -g nodemon
注:此时可能会遇到不能执行nodemon程序的问题,需要我们以管理员身份运行powershell,输入命令:set-ExecutionPolicy RemoteSigned,在键入Y,回车即可。
XMLHttpRequest
发送get请求
const xhr = new XMLHttpRequest();
let url = `http://127.0.0.1:3000?token=${token}`
xhr.open("GET", url, true);
xhr.onload = function () { };
await xhr.send(null);
console.log('res' + xhr.responseText)
xhr.abort();
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/open
其中open方法用于预设http请求方法、url、同步异步情况等;send方法是真正发送http请求的方法;onload方法用于给xhr的load事件注册一个处理函数,当请求完成时会触发load事件,此方法要放在send之前定义。
发送POST请求
var xhr = new XMLHttpRequest();
xhr.open("POST", "/server", true);
//发送合适的请求头信息
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
// 请求结束后,在此处写处理代码
};
xhr.send("foo=bar&lorem=ipsum");
调用abort方法终止连接