express模拟接口

2018-04-03 10:35:40 浏览数 (1)

1、node环境安装

  • http://www.runoob.com/nodejs/nodejs-install-setup.html

2、express安装

代码语言:javascript复制
npm install express --save

3、body-parser安装

代码语言:javascript复制
npm install body-parser

4、demo.js

代码语言:javascript复制
//引入express模块
var express = require('express');
//引入内部中间件,主要是解析post请求
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();
});

// 创建 application/x-www-form-urlencoded 编码解析
var parser = bodyParser.urlencoded({extended: false});
/******************************** 模拟接口 开始 ******************************************************/
//用户查询接口【不支持ContentEncoding=UTF-8】
app.post('/api/user/query', parser, function (request, response) {
    console.log(request.query);
    //获取URL参数
    var data = request.query;
    // 输出 JSON 格式
    const user_query = {
        "id": data.id,
        "name": data.name
    };
    console.log(user_query);
    response.json(user_query);
});
/******************************** 模拟接口 结束 ******************************************************/

var server = app.listen(9092, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("address: %s, port: %d", host, port);
});

5、启动模拟接口

代码语言:javascript复制
node demo.js

6、调用地址

代码语言:javascript复制
http://192.168.xxx.xxx:9092/api/user/query?id=user123&name=测试

7、本机调试问题

Failed to load http://192.168.xxx.xxx:9092/api/user/query?id=user123&name=测试: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.xxx.xxx:8090' is therefore not allowed access.

本机前台调试因为端口不同,会报跨域的错误。可以加下面的代码测试

代码语言:javascript复制
//设置跨域访问(这个只是测试时使用,上线的话尽量在后台处理跨域问题)
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();
});

后台使用springMVC的@CrossOrigin注解可以解决跨域问题。

代码语言:javascript复制
package com.yonyou.scf.demo.controller;

@RestController
@Api(value = "测试接口", description = "测试环境使用")
@CrossOrigin
public class demoController {

0 人点赞