开发h5项目通过ip连接到手机上访问

保证手机和电脑在同一个局域网下,用手机访问自己电脑的ip地址

一、vue项目:在package.json中添加--host 自己的电脑ip

  "scripts": {
    "dev": "vite --mode development --open --host 自己的电脑ip",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview",
  },

二、html、js项目:添加package.json文件和app.json文件,npm run dev启一个Node服务器,根目录下创建public文件夹,将项目放入public中,作为静态资源即可访问
package.json:

{
  "name": "cpic-demo",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "dev": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {},
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "request": "^2.88.2"
  }
}

app.js:

const express = require('express');
const app = express();
const port = 9000;

const fs = require('fs');  // 处理文件
const path=require('path')  // 处理文件路径
const request = require('request'); // 处理post请求

/* 
	app.use(express.json()) 
	app.use(express.urlencoded({ extended: false }))
	直接用express调用bodyParser的方法就可以了,bodyParser2019年被弃用
*/
app.use(express.json());
app.use(express.urlencoded({extended:true}));

app.use( express.static(path.join(__dirname, 'public'))); //设置静态文件的路径

const baseUrl = 'http://baseUrl';
app.get('/',(req,res) => { 
    res.writeHead(200,{'Content-Type':'text/html'})
	  fs.readFile('/index.html','utf-8',function(err,data){
	  if(err){
		  throw err ;
	  }
	  res.end(data);
	  });
});

//所有请求代理到baseUrl服务器
app.all('*', function(req, res, next) {
	//处理非图片资源的get和post请求
	if((req.method === 'GET' || req.method === 'POST') && req.headers['sec-fetch-dest'] !== 'image'){
		request({
			url: baseUrl + req.url,
			method: req.method,
			json: true,
			headers:{"content-type": "application/json",},
			body: req.body
		}, function(error, response, body) {
			if (error) {
				res.send(error);
			}else{
				// response 为转发的请求的详细内容,response.body和后面的body是同一个对象
				res.send(body);
			}
		}); 
	}else{
		// 处理图片
		request({
			url: baseUrl + req.url,
			method: "GET",
			encoding: null,
			headers: {
				'Accept-Encoding': 'gzip, deflate'
			}
		}, function (error, response, body) {
			if (!error && response.statusCode == 200) {
				res.set('Content-Type', 'image/png;');
				res.send(body);
			}
		})
	}
    
    // next();
});
app.listen(port,() => {
	console.log(`app listening at http://自己的电脑ip:${port}`)
});
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值