把之前学习的一个小例子贴出来:
前提:需安装nodejs,可以在终端中输入node -v检查是否安装成功,安装成功后才可执行下面的步骤。
1、新建一个名称为“node”文件夹
2、进入node目录下,运行npm init 生成package.json
npm init
3、安装express框架
npm install --save express
4、在node目录下新建一个app.js文件,并对app.js进行编辑
const express = require('express'); // 引入express const app = express(); //设置允许跨域访问该服务 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(); }); let allUserInfo = [{ userId: 1, userName: '小明', age: '18', address: '浙江杭州' }, { userId: 2, userName: '张三', age: '20', address: '浙江宁波' }, { userId: 3, userName: '李四', age: '21', address: '浙江温州' }]; app.get('/getUserInfo', (req, res) => { let getId = parseInt(req.query.userId); // 将userId变成Number类型 let sendValue; // 根据传过来的userId,获取用户的info,并返回给客户端 for (let i = 0, len = allUserInfo.length; i < len; i++) { if (allUserInfo[i].userId === getId) { sendValue = allUserInfo[i]; } } res.send(sendValue); });
app.post('/addUser', (req, res) => {
let query = req.body;
allUserInfo.push({
userId: allUserInfo[allUserInfo.length - 1].userId + 1,
userName: query.userName,
age: query.age,
address: query.address
});
res.send('OK');
}); const server = app.listen(3000, function () { console.log('Express app server listening on port %d', server.address().port); });
5、启动服务,在node目录下,运行node app.js
node app.js
6、这时候就可以在浏览器地址栏中输入:http://localhost:3000/getUserInfo?userId=1
7、也可以在index.html用ajax请求向3000端口服务请求数据
<!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>express-get-post</title> <style> </style> </head> <body> <script> function serialize (data) { if (!data) { return ''; } var paris = []; for (var key in data) { if (!data.hasOwnProperty(key) || typeof data[key] === 'function') { continue; } var name = encodeURIComponent(key); var value = encodeURIComponent(data[key].toString()); paris.push(name + '=' + value); } return paris.join('&'); } function request (method, url, options, callback) { var req; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { // 兼容IE7及以下版本 req = new ActiveXObject(); } req.onreadystatechange = function () { if (req.readyState === 4) { if (req.status === 200) { console.log('请求成功'); callback(req.response); } } else { console.log('请求中...'); } } url = method === 'get' && serialize(options) !== '' ? url + '?' + serialize(options) : url; let sendParams = method === 'get' ? null : serialize(options); req.open(method, url); req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); req.send(sendParams); } // 获取用户信息 request('get', 'http://localhost:3000/getUserInfo', {userId: 4}, (res) => { console.log(res); }); // 增加用户 request('post', 'http://localhost:3000/addUser', {userName: 'liming', age: '23', address: '浙江绍兴'}, (res) => { console.log(res); }); </script> </body> </html>