node+express+http-proxy-middleware做代理

來源:互聯網
上載者:User

標籤:body   blog   oct   node   問題   index   targe   ima   代理   

最近,不趕著做項目,於是想著怎樣做公司的前後端分離,這個時候想到了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 siteapp.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);});

項目結構

  

  

  

 

node+express+http-proxy-middleware做代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.