0

I am sending an HTTP POST request to insert specific username/password data on a database and for some reason, it works but it sends and registers twice or more times.

The HTTP request (instead of one, two): enter image description here

My code from the javascript file (Client Side):

 //register form script
    const form = document.getElementById('reg-form');
    if(form){
      form.addEventListener('submit',registerUser);
        console.log('event added');
    } else {
        console.log('didnt add event');
    }
    
    async function registerUser(event){
        event.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const data = { username, password };
        const options = {
            method: 'POST',
            headers: {
                'Content-Type':'application/json'
            }, 
            body: JSON.stringify(data)
        };
        try{
            const fetchResponse = await fetch('https://alfred-cipher-5000.codio-box.uk/api/register', options);
            const data = await fetchResponse.json();
            return data;
        } catch (e) {
            return e;
        }
    }

    
  return (
    <BoxContainer>
          <FormContainer id="reg-form"> 
         <Input type="text" autoComplete="off" id="username" placeholder="Full Name" />
         <Input type="password" autoComplete="off" id="password"  placeholder="Password" />
         <Input type="submit" autoComplete="off" value="Submit Form"/>
       </FormContainer>
      <Marginer direction="vertical" margin={10} />
      <Marginer direction="vertical" margin="1em" />
      <MutedLink href="#">
        Already have an account?
        <BoldLink href="#" onClick={switchToSignin}>
          Signin
        </BoldLink>
      </MutedLink>
    </BoxContainer>
  );

Code from my server side:

var fs = require('fs');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const Datastore = require('nedb')
const app = express();

const database = new Datastore('database.db');
database.loadDatabase();
app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); })

app.use(bodyParser.json());

app.listen(5000, () => console.log('listening at 5000'));

app.post('/api/register', (request, response)=> {
  console.log('new request');
  const data = request.body;
  database.insert(data);
  response.json(data);
});

This puts twice or more times on my database: enter image description here

0 Answers0