带有身份验证中间件的Graphql响应解析错误

时间:2019-02-27 22:24:02

标签: javascript node.js reactjs graphql

0

我有一个从React前端发布到的GraphQL / Koa后端API。在响应上调用return response.json()将数据向下传递到Promise链时,出现“位置0的JSON中的意外令牌O”。响应如下:

Response {type: "cors", url: "http://localhost:8000/graphql", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: true
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:8000/graphql"
__proto__: Response

主体对象是已解析的承诺,返回“ OK”,因此在位置0处出现“ O”错误。我的graphql解析器不值得指责,因为我已经使用隐式返回的JSON对象对其进行了测试,并且错误仍然存​​在。我已将isAuthenticated中间件隔离为该错误的源头,但不知道如何以不同的方式实现它来防止这种情况。下面是我的服务器设置和我的isAuthenticated中间件。

//server.js 

const Koa = require('koa')
const Router = require('koa-router')
const graphqlHTTP = require('koa-graphql');
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser')
require('dotenv').config()

const app = new Koa()
const router = new Router();

const graphqlSchema = require('./graphql/schema/index')
const graphqlResolvers = require('./graphql/resolvers/index')
const { isAuthenticated } = require('./middleware/isAuthenticated')

//middlewares
app.use(bodyParser())
app.use(cors())
app.use(isAuthenticated)


router.all('/graphql', graphqlHTTP({
   schema: graphqlSchema,
   rootValue: graphqlResolvers,
   graphiql: true,
   formatError: err => {
     console.log(err.message)
     return err.message
   }
 }));

app.use(router.routes()).use(router.allowedMethods());
//isAuthenticated.js
const jwt = require('jsonwebtoken');

const isAuthenticated = async (ctx, next) => {
  const authHeader = ctx.get('Authorization');
  if (!authHeader) {
    ctx.isAuthenticated = false;
    return next();
  }
  const token = authHeader.split(' ')[1];
  if (!token || token === '') {
    ctx.isAuthenticated = false;
    return next();
  }
  let decodedToken;
  try {
    decodedToken = jwt.verify(token, 'thisIsASuperSecretCode');
  } catch (err) {
    ctx.isAuthenticated = false;
    return next();
  }
  if (!decodedToken) {
    ctx.isAuthenticated = false;
    return next();
  }
  ctx.isAuthenticated = true;
  ctx.userId = decodedToken.userId;
  next();
}

module.exports = { isAuthenticated }

感谢您为这个长期存在的问题提出的所有建议和歉意。

0 个答案:

没有答案