Laravel Türkiye Discord Kanalı Forumda kod paylaşılırken dikkat edilmesi gerekenler!Birlikte proje geliştirmek ister misiniz?

backend-login

const login = async (req, res) => {
   try {
      const { email, password } = req.body;

      const user = await User.findOne({ email });

      if (!user) {
         return res.status(404).json({ error: 'User NOT FOUND!' });
      }

      const isValidPassword = await bcrypt.compare(password, user.password);

      if (!isValidPassword) {
         return res.status(401).json({ error: 'Password is not valid!' });
      }

      return res.status(200).json({ message: 'User logged in successfully!', user });
   } catch (error) {
      console.error("Error at creating user", error);
      return res.status(500).json({ error: 'Internal Server ERROR' });
   }

};

şimdi frontendde yakalamaya çalışıyorum
server/api/user/login.ts

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const user = await $fetch('http://localhost:5000/api/v1/auth/login', {
      method: 'POST',
      body,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    return user;
  } catch (error) {
    return {
      status: error.status || 500,
      body: { error: error.data?.error || 'Unknown error' }
    };
  }
})

store/authStore.ts

async login(newUser) {
      try {
        const data = await $fetch('/api/user/login', {
          method: 'POST',
          body: JSON.stringify(newUser),
          headers: {
            'Content-Type': 'application/json'
          }
        });
    
        this.user = data;
        console.log(data);
    
      } catch (error) {
        console.error('Error in login:', error.message || error);
        throw error;
        // console.log('Error message:', error.message || error.response?.data?.error || error);
        // throw new Error(error.message || error.response?.data?.error || 'Unknown error');
      }
    }

login.vue

const submitForm = async () => {
  try {
    await authStore.login(formData);
    console.log("Login successful");
  } catch (error) {
    console.log(error);
    // console.error("Login failed:", error.message || error.response?.data?.error || error);
    console.error("Login failed:", error.message || error);
  }
};

fakat diyelim ben emaili doğru yazdım fakat parolayı yanlış bana

{
    "status": 401,
    "body": {
        "error": "Password is not valid!"
    }
}

böyle hata dönüyor fakat Login successful dönüyor.

const submitForm = async () => {
  try {
    await authStore.login(formData);
    console.log("Login successful");
  } catch (error) {
    console.log(error);
    // console.error("Login failed:", error.message || error.response?.data?.error || error);
    console.error("Login failed:", error.message || error);
  }
};

yani catche gitmiyor try e gidiyor bunu nasıl çözebilirim.

Ayrıca terminalda da bana

 ERROR  [unhandledRejection] read ECONNRESET                       11:50:00 AM

  at TCP.onStreamRead (node:internal/stream_base_commons:218:20)

hata dönüyor.

    Daha iyisini bilen varsa yazabilir.

    server/api/user/login.ts

    export default defineEventHandler(async (event) => {
      try {
        const body = await readBody(event);
        const user = await $fetch('http://localhost:5000/api/v1/auth/login', {
          method: 'POST',
          body,
          headers: {
            'Content-Type': 'application/json'
          }
        });
    
        return user;
      } catch (error) {
        throw error;
      }
    })

    store/authStore.ts

    async login(newUser) {
          try {
            const data = await $fetch('/api/user/login', {
              method: 'POST',
              body: JSON.stringify(newUser),
              headers: {
                'Content-Type': 'application/json'
              }
            });
        
            this.user = data;
            console.log(data);
        
          } catch (error) {
            throw error.data;
          }
        }

    login.vue

    const submitForm = async () => {
      try {
        await authStore.login(formData);
        console.log("Login successful");
      } catch (error) {
        console.log(error.data);
      }
    };

    Kodlarımı böyle yaparak

    {
        "error": "Password is not valid!"
    }

    bu şeklinde hatayı console da alabiliyorum fakat bu serferde garip şekilde console da kırmızı olarak

    POST http://localhost:3000/api/user/login 404 (Not Found)

    bu hatanın previewi

    {
        "url": "/api/user/login",
        "statusCode": 404,
        "statusMessage": "Not Found",
        "message": "[POST] \"http://localhost:5000/api/v1/auth/login\": 404 Not Found",
        "stack": "",
        "data": {
            "error": "Password is not valid!"
        }
    }

    terminalda ise

     ERROR  [nuxt] [request error] [unhandled] [404] [POST] "http://localhost:5000/api/v1/auth/login": 404 Not Found
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)  
      at async $fetch2 (./node_modules/ofetch/dist/shared/ofetch.37386b05.mjs:268:15)  
      at Object.handler (./server/api/user/login.ts:4:1)  
      at async ./node_modules/h3/dist/index.mjs:1975:19  
      at async Object.callAsync (./node_modules/unctx/dist/index.mjs:72:16)  
      at async Server.toNodeHandle (./node_modules/h3/dist/index.mjs:2266:7)

    geliyor acaba nerede hata yapıyorum.

    Doğru parola ve email ile girdiğimde

    {
        "message": "User logged in successfully!",
        "user": {
            "_id": "66cdd905d9107b59c9eb221e",
            "username": "aghabala2024",
            "email": "aghabala.guluzade@gmail.com",
            "password": "$2a$10$Ta.BX/kfmCIVf0VyPQaeF.P0wuW2uxQ9MqMzolHGt.EtIr27M.xwW",
            "admin": false,
            "createdAt": "2024-08-27T13:47:49.371Z",
            "updatedAt": "2024-08-27T13:47:49.371Z",
            "__v": 0
        }
    }

    Login successful

    oluyor

    mgsmus teşekkür ederim hocam ama galiba bana yardımcı olmadı linkteki şeyler.

      aghabalaguluzade Demek istediğim şuydu:

      const login = async (req, res) => {
          const {email, password} = req.body;
      
          const user = await User.findOne({email});
      
          if (!user) {
              throw createError({
                  statusCode: 404,
                  statusMessage: 'User Not Found'
              })
          }
      
          const isValidPassword = await bcrypt.compare(password, user.password);
      
          if (!isValidPassword) {
              throw createError({
                  statusCode: 401,
                  statusMessage: 'Password is not valid!'
              })
          }
      
          return user;
      };

        mgsmus hocam bu verdiğiniz kodlar nodejs tarafının kodları.

        if (!isValidPassword) {
                 throw createError({
                    statusCode: 401,
                    statusMessage: 'Password is not valid!'
                 })
              }

        bunu eklediğimde bana

        POST http://localhost:3000/api/auth/login 500 (Internal Server Error)
        {
            "url": "/api/auth/login",
            "statusCode": 500,
            "statusMessage": "Internal Server Error",
            "message": "[POST] \"http://localhost:5000/api/v1/auth/login\": 500 Internal Server Error",
            "stack": "<pre><span class=\"stack internal\">at process.processTicksAndRejections (node:internal/process/task_queues:95:5)</span>\n<span class=\"stack internal\">at async $fetch2 (./node_modules/ofetch/dist/shared/ofetch.37386b05.mjs:268:15)</span>\n<span class=\"stack\">at Object.handler (./server/api/auth/login.ts:4:1)</span>\n<span class=\"stack internal\">at async ./node_modules/h3/dist/index.mjs:1975:19</span>\n<span class=\"stack internal\">at async Object.callAsync (./node_modules/unctx/dist/index.mjs:72:16)</span>\n<span class=\"stack internal\">at async Server.toNodeHandle (./node_modules/h3/dist/index.mjs:2266:7)</span></pre>",
            "data": {
                "error": "Internal Server ERROR"
            }
        }

        termninalda

         ERROR  [nuxt] [request error] [unhandled] [500] [POST] "http://localhost:5000/api/v1/auth/login": 500 Internal Server Error
          at process.processTicksAndRejections (node:internal/process/task_queues:95:5)  
          at async $fetch2 (./node_modules/ofetch/dist/shared/ofetch.37386b05.mjs:268:15)  
          at Object.handler (./server/api/auth/login.ts:4:1)  
          at async ./node_modules/h3/dist/index.mjs:1975:19  
          at async Object.callAsync (./node_modules/unctx/dist/index.mjs:72:16)  
          at async Server.toNodeHandle (./node_modules/h3/dist/index.mjs:2266:7)

        hatalarını verdi