接口 (软件类接口) 是指对协定进行定义的引用类型. 其他类型实现接口, 以保证它们支持某些操作. 接口指定必须由类提供的成员或实现它的其他接口. 与类相似, 接口可以包含方法, 属性, 索引器和事件作为成员.
Node.JS 接口是使用 Node.JS 实现的包含方法, 属性, 索引器和事件作为成员对协定进行定义的引用类型. Node.JS 可以通过 express 模块来写接口.
一个 Node.JS 接口:
db 部分公共
- var MySQL = require('mysql');
- var dbMsg = {
- host : 'localhost',
- user : 'root',
- password : '123456',
- database : 'app_pro'
- }
- var connection = MySQL.createConnection(dbMsg);
- connection.connect();
- module.exports = connection;
App.JS
- var express = require('express');
- var App = express();
- var bodyParser = require('body-parser');
- // 获取数据库连接对象
- var connection = require('./mysql/db');
- // 处理 post 字段请求
- App.use(bodyParser.JSON());
- App.use(bodyParser.urlencoded({ extended: true }));
- // 处理跨域请求
- App.all("*", function(req, res, next) {
- res.header("Access-Control-Allow-Credentials", true);
- res.header("Access-Control-Allow-Origin", "*");
- res.header("Access-Control-Allow-Headers", "X-Requested-With");
- res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
- res.header("Content-Type", "application/json;charset=utf-8");
- next();
- });
- App.get('/',function(req,res){
- res.send('请求 home 成功');
- })
- // 用户登录
- App.post('/user/login', (req,res) => {
- var name = req.body.username;
- var passwd = req.body.password;
- var userStr = `select * from user where username="${name}" and password="${passwd}"`;
- connection.query(userStr,function(err,result){
- if(err){
- throw err;
- }else{
- res.send(result)
- }
- })
- })
- // 用户注册
- const port = 3001;
- App.listen(port, () => {
- console.log('Express server listening on port' + port);
- });
来源: http://www.css88.com/qa/node-js/12028.html