項目結構
就是建立app.js 和 index.html 然後安裝一個express
app.js
var express = require('express');
var app = express();
//這裏就是跨域用的,因爲你用ajax請求的話是需要跨域的,因爲不是在同一個域裏,不懂的話可以百度一下,反正這裏不理
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
app.get('/', function (req, res) {
console.log("主頁");
res.send('後臺主頁');
})
app.get('/api', function (req, res) {
console.log("假設這裏是api接口");
res.send({message:'後臺傳來的數據',success:true}); //這裏就是傳回給前臺的數據呀,我這裏是 ‘{message:'後臺傳來的數據',success:true}’,等等你注意前臺接收
})
var server = app.listen(8081, function () {
console.log('running at port 8081')
})
記住要啓動這個先,因爲我沒有用前端模板引擎,所以先啓動這個app.js ,然後在用瀏覽器打開index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
<script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script>
</head>
<body>
<button id="btn">請求數據</button>
<script>
$('#btn').click(function(){
$.get('http://127.0.0.1:8081/api',{message:'這是傳到後臺的數據'},function(data,status){//這是一個回調函數
console.log(data);//這樣就是打印我們剛剛的{message:'後臺傳來的數據',success:true}
console.log(data.message + '|' + data.success);
})
})
</script>
</body>
</html>
按下F12 點擊請求數據,看控制檯:
試一下這個。晚安!!