react+express个人博客(二).express+mongoose后端

源码: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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,476评论 25 708
  • 我们都听过「stay hungry,stay foolish」这句话。这在新时代尤其重要。面对爆炸的信息,要想不被...
    思想筆記阅读 401评论 1 4
  • 原来她的性格并不内向,原来她的笑容可以灿烂,原来她的交谈滔滔不绝。似乎后来别人面前的她和当初我面前的她在我印象中不...
    爬小爬阅读 165评论 0 0
  • 见过我哭的人很多,可知道我为什么哭的人很少。见过我笑的人很多,可知道我是否快乐的人很少。 我觉得这个世界上有很多很...
    桃喜咩阅读 538评论 0 0
  • 无意间听见节目里龚琳娜唱的小河淌水,空灵婉转,曲境通幽,直入人心。才知道自己忽视了这位不甚炒作的艺术家,和灵魂歌者...
    爱吃糖糖的小魔女阅读 190评论 0 0