Api form with credentials

Hello!
I'm really struggling with a project where the backend was already made on NodeJS.
I need to create the frontend also on NodeJS and I'm using Wappler for that (which in the end will be on different domain/port).

For testing, backend is :3000, frontend :4000 and for login and storing cookies, I ran in some issues.

This doesn't store cookies:

<form is="dmx-api-form" id="apiform1" action="http://localhost:3000/auth/login" method="post" post-data="json">
    <input id="text1" name="email" type="text" class="form-control">
    <input id="text2" name="password" type="text" class="form-control">
    <button id="btn1" class="btn" type="submit">Login</button>

But this, does:


<form id="loginForm">
    <input id="email" name="email" type="text" class="form-control">
    <input id="password" name="password" type="password" class="form-control">
    <button id="loginButton" class="btn" type="submit">Login</button>
</form>
<script>
    document.getElementById('loginForm').addEventListener('submit', async (event) => {
  event.preventDefault();
  
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;

  const response = await fetch('http://localhost:3000/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    credentials: 'include',
    body: JSON.stringify({ email, password })
  });
</script>

If I comment credentials: 'include', the cookies are not being stored, so I think the issue is going on that direction.

Is it possible to send credentials on an API form?

Thanks!

Convert the from to a Server Connect form and you will see the Credentials tick box, is this what you are after @franse ?

EDIT!
Discount that I see it is an API form! Hmmm....

What if you add credentials="true" to the form?

1 Like

Well, that was easy, haha, It's not a server connect, but still, it works:

const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.post('/login', async (req, res) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return res.status(400).json({ message: 'Faltan datos' });
  }

  try {
    const user = await User.findOne({ where: { mail_users: email, password_users: password } });

    if (!user) {
      return res.status(401).json({ message: '401' });
    }

    req.session.userId = user.id_users;

    res.cookie('userId', user.id_users, {
      httpOnly: true,
      secure: false,
      sameSite: 'Lax',
    });

    res.json({ message: 'Login ok' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error', error: error.message });
  }
});

Don't really know how, but it works, thanks @Cheese
PS: Also credentials="true" works, seems I forgot to restart the app after saving the file, would be nice if its automatic

1 Like