codedamn

Simple JWT Auth Example

Created by Codedamn about a year ago

0

No description provided

6 Comments

    0

    Mysql How do i connect to mysql db?

    @wenk

    Gerhard Wenk

    @wenk

    0

    TypeError: NetworkError when attempting to fetch resource Hey I followed every single line of code, although I get that error. It seems NextJS API create issue (maybe CORS). Here is my page/index.tsx code:

    import { useEffect, useState } from "react";
    import jwt from "jsonwebtoken";
    
    export default function Home() {
      const [username, setUsername] = useState<string>("");
      const [password, setPassword] = useState<string>("");
      const [message, setMessage] = useState<string>("Yet not get it from server");
      async function submitForm(e) {
        const res = await fetch("/api/login", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ username, password }),
        }).then((t) => t.json())
        const token = res.token;
        console.log(`Get token:`, token);
        if (token) {
          const json = jwt.decode(token) as { [key: string]: string };
          setMessage(`Welcome ${json.username}`);
        } else {
          setMessage(`Something went wrong`);
        }
      }
      return (
        <div>
          <h1>{message}</h1>
          <form>
            <input
              type="text"
              name="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
            <br />
            <input
              type="password"
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <br />
            <input type="submit" value="Login" onClick={submitForm} />
          </form>
        </div>
      );
    }
    

    Here is my api/login.tsx code:

    import { NextApiRequest, NextApiResponse } from "next";
    import jwt from "jsonwebtoken";
    
    const KEY = "IAMTOOMUCHSECRETKEY";
    
    export default function (req: NextApiRequest, res: NextApiResponse) {
      console.log(`From api/login`, req.body);
      if (!req.body) {
        res.statusCode = 404;
        res.end("Error");
        return;
      }
      const { username, password } = req.body;
      res.json({
        token: jwt.sign(
          {
            username,
            admin: username === "admin" && password === "password",
          },
          KEY
        ),
      });
    }
    

    \

    @xenondu

    XenonDU

    @xenondu

    0

    Hey! Your web is much faster in low network connection ☺️

    @deepakvish8

    Deepak Vishwakarma

    @deepakvish8

    0

    Why do you use ".then()" after the await promise? Won't the response from the server already be JSON?

    @cjsperber

    C.J.

    @cjsperber

    0

    hard to mug up

    @tusharjade99

    Tushar Jade

    @tusharjade99

    0

    HTML 2.0, the first official standard spec for HTML came out in 1995. I am not sure why you mentioned 1980 style, twice. Netscape browser was launched in 1994, I think.

    @prasadn

    Prasad Nageshkar

    @prasadn

Your comment