React让前端飞Web前端之路

react+express个人博客(二).express+mon

2018-02-02  本文已影响46人  Evan_zhan

源码:github:

https://github.com/xiaofengz/react-blog

xiaofengz/react-blog

现在开始在项目加入express~在本地搭个服务器,并为自己写接口。

一.进入项目根目录

首先你需要安装 Node.js 环境 这里不再做介绍,

1.安装Express
 npm install express -g
  npm install express-generator -g

2.初始化项目
  express server(项目名称) 
3.执行如下命令:
1.cd server//进入项目根目录
2.npm install  //安装依赖 

此时整个项目目录结构为

image

前端启动命令为npm run dev

后端启动命令为 npm start

搭建完项目架构。现在演示一个最简单的接口。

获取用户信息

1.点击页面 个人主页 发送请求

2.通过接口 去本地node服务器请求数据,返回数据。

效果如下:

image

首先,前端部分:

1.Header组件 绑定onClick事件

  import UserService from 'SERVICES/userService';

  jumpToPersonalPage () {
    UserService.fetchUserInfo({
           id:"1"
       })
   }
  <li onClick={this.jumpToPersonalPage.bind(this)}>
     <a>
         <i className="iconfont icon-user" ></i>个人主页
     </a>
  </li>

2. userServise.js

import xhr from "UTILS/xhr";
import urls from "CONSTS/urls";

class UserService {
  constructor() {
    this.url = urls["url"];
   }
  // 请求用户信息demo
  fetchUserInfo(data) {
     method: "get",
      url: "http://127.0.0.1:9001/users/getUserInfo",
      params: {
        ...data
      }
   });
 }
}

export default new UserService();

3. xhr.js (axios请求统一处理)

// 请求集中处理
import axios from "axios";
import {notification} from 'antd';

let axiosInstance = axios.create();

axiosInstance.interceptors.request.use(config => {
    // config.headers['Content-Type'] = 'application/json;charset=utf-8';
    // config.headers['x-app-code'] = 'LM-ALG';  //这里可能需要
    config.withCredentials = true;
    return config
}, error => {
    return Promise.reject(error)
});

/**
 * Requests a URL, returning a promise.
 *
 * @param  {object} [options] The options we want to pass to "axios"
 * @return {object}           An object containing either "data" or "err"
 */
const xhr = ({method='get', headers, ...options}) => {
    //前提是header不存在
    if(!headers){
        if(method==='get'){
            headers={'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}
        }else if(method === 'post'||method==='put'){
            headers={'Content-Type':'application/json;charset=utf-8'}
        }
    }
    return axiosInstance({method, headers, ...options})
        .then((response) => {
            if (response.status >= 200 && response.status < 300) {
                return response;
            } else {
                handleError(response)
            }
        })
        .then((response) => {
            const {data} = response;
            if (data.errcode === 0) {
                return data;
            } else {
                handleError(response);
            }
        })
        .catch((error) => {
            if (error.code) {
                notification.error({
                    message: error.name,
                    description: error.message,
                });
            }
            if ('stack' in error && 'message' in error) {
                notification.error({
                    message: `请求错误: ${url}`,
                    description: error.message,
                });
            }
            return error;
        });
};

function handleError({data = {}, status}) {
    const {errcode} = data;
    if (errcode === 3) {
        //无权限处理
        console.log(new Error('没有权限'))
        //...
    } else {
        const error = new Error(data.errmsg || status + '错误');
        error.response = response;
        throw error;
    }
}

export default xhr;

后端部分:

1.routes>user.js (定义user模型)

function User(){
    this.name;
    this.city;
    this.age;
}
module.exports = User;

2.routes>users.js

var express = require('express');
var router = express.Router();
var URL = require('url'); //请求url模块
var User = require('./user'); //引入user.js
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.get('/getUserInfo',function(req,res,next){
  var user = new User();
  var params = URL.parse(req.url,true).query; // 解析参数

  if(params.id == '1'){
      user.name = "Evan";
      user.age = "23";
      user.city = "杭州";
  }else{
      user.name = "SPTING";
      user.age = "1";
     user.city = "杭州市";
  }

  var response = {status:1,data:user};
  res.send(JSON.stringify(response));
})
module.exports = router;
上一篇 下一篇

猜你喜欢

热点阅读