Save the data from the input form into a JSON file

I'm new to using Express and I want to store the input field value in my JSON file. When I try to do this, I get an error message: POST http://localhost:5500/userData 405 (Method Not Allowed). From what I understand, it seems like the server is not supporting my request for the path. In my code, I have server.js, index.html, and user.js files.

Thank you in advance!

HTML:

<form class="modal-form" id="form" method="post" action="/data/userData.json">
    <h1>Create your account!</h1>
    <div class="form-validation">
        <input class="modal-input" type="text" id="createUserName" name="name" placeholder="Enter your name"></input>
    </div>

    <div class="form-validation">
        <input class="modal-input" type="password" id="createUserPassword" name="password" placeholder="Enter your password"></input>
    </div>

    <Button type="submit" class="modal-input-btn" value="Sign Up" onclick="createUser()">Sign up</Button>

    <span class="modal-input-login">Already have an account? Login <Button type="button" onclick="document.getElementById('modal-login').style.display='block',document.getElementById('modal').style.display='none'">here</Button></span>
</form>

user.js:

let users = [];
function createUser() {
let userName = document.getElementById('createUserName');
let userPassword = document.getElementById('createUserPassword');

let user = {
name: userName.value,
password: userPassword.value
}

fetch("http://localhost:5500/data/userData", {
method: "POST",
body: JSON.stringify(user),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => {
console.log(json);
users.push(user); // Pushes the user to the array of users
console.log(users); // Logs the updated array of users
})
.catch(err => console.error(err));
}

document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
});

server.js

const express = require('express');
const cors = require('cors');
const fs = require('fs');
const app = express();

const port = 5500;

app.use(cors()); 
enable CORS

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/data/userData', (req, res) => {
const data = JSON.stringify(req.body);

fs.writeFile('./data/userData.json', data, (err) => {
if (err) {
console.error(err);
res.status(500).send('Error writing to file');
} else {
res.send('Data written to file');
}
});
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Answer №1

Allow me to correct your code

const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();

 const port = 5500;

 app.use(cors()); // Enable CORS

 app.use(express.json());
 app.use(express.urlencoded({ extended: true }));

 app.use(express.static(__dirname + '/public'));

 app.get('/',(req,res)=>{

  res.sendFile('index.html');
  });

  app.post('/userData', (req, res) => {
  const data = JSON.stringify(req.body);

  console.log(data);
  fs.writeFile('./data/userData.json', data, (err) => {
  if (err) {
  console.error(err);
  res.status(500).send('Error writing to file');
  } else {
  res.send('Data written to file');
  }
 });
  });

 app.listen(port, () => console.log(`Example app listening on port 
  ${port}!`));










  <!DOCTYPE html>
  <html>
  <head>
  <title>Page Title</title>
  </head>
  <body>


   <form class="modal-form" id="form" method="post" 
    action="/data/userData.json">
    <h1>Create your account!</h1>
    <div class="form-validation">
        <input class="modal-input" type="text" id="createUserName" 
    name="name" placeholder="Enter your name"></input>
    </div>

    <div class="form-validation">
        <input class="modal-input" type="password" 
    id="createUserPassword" name="password" placeholder="Enter your 
    password"></input>
    </div>

     <Button  type="submit" class="modal-input-btn" value="Sign Up" 
  onclick="createUser()">Sign up</Button>

    <span class="modal-input-login"> Already have an account? Login 
       <Button type="button" 
    onclick="document.getElementById('modal- 
        login').style.display='block',
             document.getElementById('modal').style.di 
         splay='none'">here</Button></span>
      </form>

     <script>

 let users = [];
 function createUser() {
 let userName = document.getElementById('createUserName');
 let userPassword = document.getElementById('createUserPassword');

  let user = {
   name: userName.value,
   password: userPassword.value
   }
   console.log(user);
   fetch("http://localhost:5500/userData", {
   method: "POST",
   body: JSON.stringify(user),
    headers: {
    "Content-type": "application/json; charset=UTF-8"
    }
   })
 .then(response => response.json())
 .then(json => {
  console.log(json);
   users.push(user); // Pushes the user to the array of users
   console.log(users); // Logs the updated array of users
  })
  .catch(err => console.error(err));
   }

    document.getElementById('form').addEventListener('submit', (e) 
 => 
{
    e.preventDefault();
 });
  </script>
  </body>
  </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Fetch() function is triggering a resource blockage due to CORS restrictions

App.js : import React from 'react'; import './App.css'; class App extends React.Component { state = { character : {} }; componentDidMount() { fetch("https://jobs.github.com/positions.json?description=basf") .the ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Designing a website similar to sevenly.org using jquery: A step-by-step guide

My understanding of javascript and jquery is at a beginner level. I am interested in creating a design similar to Sevenly, where one page/div moves over another. I'm not sure where to begin with this. Any advice or ideas on how to implement this effec ...

Guidelines for displaying a React component upon landing

I am a beginner in react app development and I am currently trying to add a component that loads when the app opens. However, I encountered an issue where the console displays the message Matched leaf route at location "/" does not have an elemen ...

Creating a script in JavaScript to execute a command or query after midnight

I have a query regarding MongoDB and JavaScript (Express.js). Here is the scenario: I am working on developing a backend service for movies and TV series. I have already set up basic routes and functions. One of my requirements is to select a movie from ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

Tips for importing all global Vue components in a single file

I currently have a large Vuejs application where I imported all my components globally in the app.js file. While it's functioning well, I believe reorganizing the component imports into a separate file would improve the overall structure of the projec ...

Troubleshooting a Problem with AppCheck Firebase reCaptcha Configuration

Currently integrating Firebase with my Next.js project. I've been attempting to configure AppCheck reCaptcha following the documentation and some recommendations, but I encounter an issue when running yarn build The build process fails with the foll ...

What is the best way to retrieve a valid JSON output from a response in Zend Framework 3?

Recently, I have been working on developing a client to interact with an API... use Zend\Http\Client; use Zend\Http\Request; use Zend\Json\Json; ... $request = new Request(); $request->getHeaders()->addHeaders([ &ap ...

Redux is set to return a proxy object in place of the actual state

I'm encountering an issue where I am getting a proxy object when trying to access my initial state in redux. How can I properly access the contents of my state? When attempting to retrieve a large 2D array for a grid, it seems to work fine with small ...

When submitting a form using Node.js Express, req.body may return an empty object

I am sending a post request to '/' with a basic text input and am anticipating to see the data entered in req.body.course. However, when I try to log req.body.course, I am receiving an empty object in return. HTML <html> <head>& ...

Differences between using Constructor(props) and super(props) versus simply using constructor() and super() in React Development

Although this question has been asked numerous times, it still remains unclear to me. Many have simply stated: Pass props to constructor if you want to access this.props there Here is another example of the answer The official documentation states tha ...

Issue encountered with Node.js port authorization on Windows 10

Encountering an issue when attempting to launch a server in Express.js resulting in the following error: [nodemon] 2.0.12 [nodemon] at any time, enter `rs` to restart. [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] sta ...

Troubleshooting a problem with $addToSet and $each in Mongo and Node.js

I'm facing an issue while using $addToSet to add an array of Strings to a MongoDB database. The Object setup is defined as follows: var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('Co ...

Effectively generating observables that extract a designated element from a collection of observables

Within my application, I am utilizing a RxJS subject to broadcast changes within a collection. Each time the collection is updated, the subject emits the new contents as an array format. let collectionSubject = new Rx.BehaviourSubject(); collectionSubjec ...

Using PHP to track the number of clicks on a specific div element

Although I am not well-versed in javascript, I have incorporated it into my website to enhance its appearance. One of the features I've added is a popup that appears when a user clicks on a specific div element to display additional information. In ad ...

Retrieve data via POST and utilize it to instantiate an object within PHP, subsequently serializing the object into JSON format

Context: Upon receiving transaction initialization parameters through POST for a payment service, the goal is to utilize these parameters in PHP to generate a 'Deposit' object. Subsequently, this deposited object needs to be JSON serialized and ...

Launch the messaging app with ng-href

Looking for a way to open the SMS app using ng-href, I encountered a strange issue. When I use: href="sms:?body=text" The SMS app opens on my mobile device as expected. However, if I try: ng-href="sms:?body=text" The SMS app does not open on my device. ...

Here's a quick guide on instantly clearing notifications on an Android device

My application displays a notification when I receive new data. The service sends the login time to JSON, which is then checked on the server for any new available data. If there is new data, it retrieves the number of new entries and timing of the latest ...

Choose several files to upload, as displayed in an HTML table

I am trying to determine the number of files selected using a file selection tag that populates an HTML table with a button in each row. My goal is to identify the total count of selected files when clicking on the button in the same row and then proceed ...