Node.js res.send 不是函数(微信小程序)
Node.js res.send is not a function (wechat miniprogram)
我正在为我的前端写一个api,过程是,前端发送一个字符串给后端,后端解码后发回代码。
const router = require('koa-router')({
prefix: '/weapp'
});
router.post("/openid", async (req, res) => {
const Ut = require("../common/utils");
try {
let grant_type = 'authorization_code'
let appid = config.appId
let secret = config.appSecret
let code = req.accept.headers.accept
console.log('req code: ', code);
let opts = {
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=' + grant_type
}
let r1 = await Ut.promiseReq(opts);
r1 = JSON.parse(r1);
console.log('r1 is:', r1);
openid = r1.openid
res.send(openid)
}
catch (e) {
console.log(e);
res.json('');
}
})
res.send(openid)
应该发送openid,但是我收到的是{code: -1, error: "res.json is not a function"}
。而且我没有看到变量 res
的定义被重载。请帮帮我~
您的代码被捕获并运行 res.json('')。尝试将其更改为 res.json(null) 或 res.json({})
问题已解决。
代码router.post("/openid", async (req, res) => {
使用Express框架,而微信使用Koa2框架,所以async()
中的参数有点不同。
在Koa2中,我们应该写成router.post("/openid", async (ctx, next) => {
。本例中ctx.response和ctx.request分别代表express中的res和req。
我正在为我的前端写一个api,过程是,前端发送一个字符串给后端,后端解码后发回代码。
const router = require('koa-router')({
prefix: '/weapp'
});
router.post("/openid", async (req, res) => {
const Ut = require("../common/utils");
try {
let grant_type = 'authorization_code'
let appid = config.appId
let secret = config.appSecret
let code = req.accept.headers.accept
console.log('req code: ', code);
let opts = {
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=' + grant_type
}
let r1 = await Ut.promiseReq(opts);
r1 = JSON.parse(r1);
console.log('r1 is:', r1);
openid = r1.openid
res.send(openid)
}
catch (e) {
console.log(e);
res.json('');
}
})
res.send(openid)
应该发送openid,但是我收到的是{code: -1, error: "res.json is not a function"}
。而且我没有看到变量 res
的定义被重载。请帮帮我~
您的代码被捕获并运行 res.json('')。尝试将其更改为 res.json(null) 或 res.json({})
问题已解决。
代码router.post("/openid", async (req, res) => {
使用Express框架,而微信使用Koa2框架,所以async()
中的参数有点不同。
在Koa2中,我们应该写成router.post("/openid", async (ctx, next) => {
。本例中ctx.response和ctx.request分别代表express中的res和req。