微信小程序post请求本地egg.js接口

嗯,刚上手微信小程序,和egg.js,拉项目中遇到挫折,折腾了2小时,发现没有什么参考文献,那就自己写一个吧。

两个重要的坑,先填一下

  • 坑1:wx.request()的post请求发不出去,不允许http
    脱坑方案:在『微信开发者工具』:设置>>项目设置>>勾选『不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书』

  • 坑2:egg.js默认加载了koa2的crsf验证机制,小程序又不允许cookie,就得取消crsf接口验证了

// config.default.js

// 关闭csrf
config.security = {
  csrf: {
    enable: false,
    ignoreJSON: true,
  },
  // 白名单
  domainWhiteList: [ 'http://localhost:8080' ],
};

// 允许规则
config.cors = {
  allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};

填完上面两个坑,接下来看一下简单的Demo

1、小程序发POST请求

wx.request({
  url: 'http://127.0.0.1:7001/fuck',
  method: 'POST',
  header: {
    'content-type': 'application/json'
  },
  dataType: 'json',
  data: {
    fuck: 'fuck',
  },
  success: res => {
    console.log(res); //结果 {'1'}
  }
})

2、egg.js

  • 2.1 egg.js路由
// router.js
router.post("/fuck", controller.fuck.test);
  • 2.2 egg.js控制器
// app/controller/fuck.js
'use strict';
const Controller = require('egg').Controller;

class FuckController extends Controller {
  async test() {
  	// 打印ajax.post data参数
    console.log(this.ctx.request.body); //{fuck:'fuck'}
    // 返回
    this.ctx.body = '1';
  }
}

module.exports = FuckController;

你可能感兴趣的:(egg.js)