1 (计算机网络)我们常用的网络协议有
392 2023-04-03 03:05:24
npm install express -d
这个是express.js里面的代码let express = require('express'); // 引入服务框架let app = express() // 让他执行app.get('/user',function(req,res){ // 可以get/post请求 // req是请求的信息 // res是相应回去的信息 res.json({name:'zzf'}) // 响应体里设定一个json格式字符串})app.listen(8000,function(){ // 启动localhost:8000/user就可以访问这个数据 console.log('8000端口号服务已经启动');})
这个是webpack里面的配置 devServer: { port: 7777, open: true, contentBase: 'static', hot: true, proxy:{ // 启动代理 '/api':{ target:'http://localhost:8000', // 目标路径, secure: false, // true就是https false就是http pathRewrite:{'^/api':''}, // 路径重写 // changeOrigin:true, // 是否把请求的基础路径改成服务器地址 =>有的时候服务器会多识别这一项 // changeOrigin // 也是会把请求头里的路径更改,就是req的数据 } } },
这种是不需要后台配合,直接返回指定数据
devServer: { port: 7777, open: true, contentBase: 'static', hot: true, before:function(app,server){ // // //before是在请求之前,就直接处理返回一个数据,不用后端配合 app.get('/api/user',function(app,res){ // app部分就是自动识别端口号,自己按照我们传入的路径传入,不会产生跨域 res.json({custom:'111'}) // 这个就是自动返回json格式的字符串了 }) } },
右键Run code页面访问 http://localhost:8000/user 就可以访问这个数据
跨域:本地服务(devServer)启动为7777 服务器是8000需要在webpack.config.js里面的devServer里做代理修改