简体   繁体   English

如何在graphql node.js中使用jwt

[英]how to use jwt with graphql nodejs

Hello am new to graphql i want to create a signup page that when ever a user signs up his id and role in the users table in mysql data base will be encrypted with jwt, but when i tried it, it didnt return any thing,it returned this with graphiQL 你好,graphql的新手,我想创建一个注册页面,当用户在mysql数据库中的用户表中注册其ID和角色时,将使用jwt对其进行加密,但是当我尝试使用它时,它没有返回任何东西,它用graphiQL返回了这个

{
  "data": {
    "registerUser": null
  }
}

import models from '../../../models/index.js';
import User from '../../types/user.js';
import UserInput from '../../inputs/user.js';
const jsonwebtoken = require('jsonwebtoken')
require('dotenv').config()

export default {
    type: User,
    args: {
        user: {
            type: UserInput
        }
    },
    resolve (_,args) {
        models.user.create({ 
            name: args.user.name,
            email: args.user.email,
            password: args.user.password,
            role:"Student"
        }).then(function(newUser) {
            return jsonwebtoken.sign(
                { id: newUser.id, role: newUser.role },
                process.env.JWT_SECRET,
                { expiresIn: '1y' }
              )
        });
    }
};

pls how can i solve this problem so that it will return the jwt token 请问我该如何解决这个问题,以便它将返回jwt令牌

I think you only missed a return statement before models.user.create : 我认为您只错过了models.user.create之前的return语句:

resolve (_,args) {
  return models.user.create({ 
    name: args.user.name,
    email: args.user.email,
    password: args.user.password,
    role:"Student"
  }).then(function(newUser) {
    return jsonwebtoken.sign(
      { id: newUser.id, role: newUser.role },
      process.env.JWT_SECRET,
      { expiresIn: '1y' }
    )
  });
}

It seems like you're interested in authentication with JWT and GraphQL. 似乎您对使用JWT和GraphQL进行身份验证感兴趣。 I think it's better to use the context and set the JWT to a cookie. 我认为最好使用上下文并将JWT设置为cookie。 I wrote a short article about this if you're interested. 如果您有兴趣,我写了一篇简短的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM