angular 代理接口,node连接本地mysql,自定义接口

一: 连接数据库

1、启动node(配置如下)

var express = require('express')
var bodyParser = require("body-parser")
var app = express()
app.all('*', function(req, res, next) {  
    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("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8")
    next()
})
// 这两行是post获取参数(repress已分离body-parser组建)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
//app.use('/upload', express.static('upload'))
app.use('/', require('./test.js'))
app.listen(3000, ()=> {
  console.info('启动成功')
})

2、连接mysql,连接数据表(创建test.js,上面要应用)

var express = require('express')
var router = express.Router()
var mysql = require('mysql')
var multiparty = require('multiparty')
var fs = require("fs")
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'jay',
port: '3306'
})
connection.connect()
/*通过id搜索用户*/
router.get('/query', function(req, res, next) {
  connection.query(`select * from one where id=${req.query.userId}`, function(error, results, fields) {
    if (error) {
      console.info('error')
      res.send(error)
    } else {
      res.send(results)
    }
  })
})

二、定义接口(接口名字是text.js自己定义)

import http from 'axios'
export default {
  // 获取用户
  getUser(param = {}) {
    return http.get('api/user', {params: param})
  },
  // 查询用户
  serachUser(param = {}) {
    return http.get('api/query', {params: param})
  },
  // 登录
  userLogin(param = {}) {
    return http.get('api/createUser', {params: param})
  },
  // 注册用户
  addNewUser(params = {}) {
    return http.post('api/addNewUser', params)
  },
  // 删除用户
  deleteUser(id) {
    return http.delete(`api/delete?userId=${id}`)
  },
  // 添加用户
  addUser(params = {}) {
    return http.post('api/add', params)
  },
  // 修改用户
  updateUser(params = {}) {
    return http.post('api/update', params)
  }
}

三、angualr代理接口(在项目自定义文件),target(node监听地址),pathRewrite(api代表这个地址,就是接口文档的api)

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": "false",
    "changeOrigin": "true",
    "pathRewrite": { "^/api": "" }
  }
}

四、在页面使用

 import http from '../../api/user';

 getData() {
    let param = {
      pageIndex: this.page,
      pageSize: 10,
      type: this.filter.type ? this.filter.type : null,
      value: this.filter.value ? this.filter.value : null
    }
    http.getUser(param).then(r => {
      this.userData = r.data.list
      this.totalPages = r.data.total
    }).catch(r => {})
  }

五、亲测有效,不好之处,请指教

 

posted @ 2018-08-21 16:20  LWJ_jay  阅读(576)  评论(0编辑  收藏  举报