最近,不赶着做项目,于是想着怎样做公司的前后端分离,这个时候想到了nodejs,于是打算今天做一个代理的demo,其实代码很简单,但是一直卡在一个地方,现在问题解决了,贴上代码和截图。
html
<!DOCTYPE html> <html> <head> <title>首页</title> <meta charset="utf-8"> <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> <style type="text/css"> .hello{ color: #428bca; } </style> </head> <body> <h3>这是index页面</h3> <span class="hello">你可以点击这里</span> <script type="text/javascript"> $(function(){ var contextPath = ‘http://localhost:3000‘; $(‘.hello‘).on(‘click‘,function(){ $.ajax({ type:‘get‘, data:‘click‘, url:contextPath+‘/api/hello‘, success:function(data){ console.log(data); }, error:function(data){ console.log(data); } }) }) }) </script> </body> </html>
localhost:3000服务端的代码
const express = require(‘express‘); const proxy = require(‘http-proxy-middleware‘); const app = express(); app.use(express.static(‘public‘)); //app.use(express.static(‘client‘)); // Add middleware for http proxying const apiProxy = proxy(‘/api‘, { target: ‘http://localhost:8080‘,changeOrigin: true }); app.use(‘/api/*‘, apiProxy); // Render your site app.get(‘/index.htm‘, function(req,res){ res.sendFile(__dirname+‘/src/index.html‘); }); app.listen(3000, () => { console.log(‘Listening on: http://localhost:3000‘); });
localhost:8080服务上的代码
var express = require(‘express‘); var app = express(); app.use(express.static(‘public‘)); var server = app.listen(8080,function(){ var host = server.address().address; var port = server.address().port; console.log(‘应用实例,访问地址为 http://%s:%s‘,host,port); }) app.get(‘/api/hello‘, function(req,res){ let data = {} data["name"] = "lucy"; data["age"] = "23"; res.send(data); });
项目结构截图
时间: 2024-12-28 22:57:11