I am currently experiencing issues with the app post feature as it is failing to generate any output

var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = 3000;
const fs = require('fs');

// establishing connection to MongoDB using Mongoose
var mongoose = require("mongoose");

// Implementing bodyParser for handling JSON and urlencoded data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })

// defining schema for the database
var nameSchema = new mongoose.Schema({
 firstName: String,
 lastNameName: String
});

// creating a model based on the defined schema
var User = mongoose.model("User", nameSchema);

// serving index.html file when accessing root route
app.use("/", (req, res) => {
 res.sendFile(__dirname + "/index.html");
});

// route for posting data
app.post("/addname", (req, res) => {
 console.log("nnnnnn")
 console.log(req.body.firstName)
 var myData = new User(req.body);
 myData.save()
 console.log(myData);
 fs.writeFile(__dirname +"/data.json",myData, function(err){
   if(err) {
     return console.log(err);
   }
   console.log("The file is saved ");
 })
 console.log(myData)
})

// starting server and listening on specified port
app.listen(port, () => {
 console.log("Server listening on port " + port);
});

1) Utilizing express to post data into the database and also storing it in a file for verification.

2) The app.post method seems to not be functioning as expected, despite attempts to debug with console.log statements.

3) Unable to retrieve output or any specific errors while executing the code. Seeking assistance for resolution.

Answer №1

This code lacks error handling and response handling functionality. To improve readability, consider utilizing the post method with async/await:

app.post("/addname", async (req, res) => {
  console.log("nnnnnn")
  console.log(req.body.firstName)
 var myData = new User(req.body);
 await myData.save()
 console.log(myData);
 fs.writeFileSync(__dirname +"/data.json", myData)
 console.log(myData)
})

Answer №2

Don't forget to include next() in your app.use function

var User = mongoose.model("User", nameSchema);



app.use("/", (req, res, next) => {
  res.sendFile(__dirname + "/index.html");
  next();
});
// Data is now being posted



app.post("/addname", (req, res) => {
  console.log("Posting data...")
  console.log(req.body.firstName)
 var myData = new User(req.body);
 myData.save()
 console.log(myData);
 fs.writeFile(__dirname +"/data.json", myData, function(err){
   if(err) {
     return console.log(err);
   }
   console.log("File saved successfully!");
 })
 console.log(myData)

})

// Fetching the data


app.listen(port, () => {
 console.log("Server running on port " + port);
});

Answer №3

Each request is directed to the app.use code block. This means that every request that comes through will pass through this middleware:

app.use("/", (req, res) => { ... });

Be sure to place it below the

app.post("/addname", (req, res) => { ... });

app.use is utilized for mounting middlewares in the request-response chain. Therefore, any request that matches the / path (essentially all requests) will be handled by this middleware. It's recommended to define your routes first and then set up the middleware at the end.

UPDATE:
Here's a simple mcve sample that I tested locally:

const express = require('express');
const fakeData = function(){
    return {
        s: "fakeData"
    }
}
const app = express();
const port = 8181
const path = require('path')
app.get("/a", (req,  res) => {
    return res.json({d:'yay'});
   
   });
app.use('/',(req,res)=>{
    return res.json(fakeData());
})

app.listen(port, () => {
    console.log(`Server started on PORT ${port}`);
});

Since every request passes through a mounted middleware, when you make a GET/POST/ANYTHING call to

localhost:8181/<abosulutely_any_path>
, it will go through the app.use as it functions as a middleware and will respond with { s: "fakeData" }.

However, if you make a GET call to http://localhost:8181/a, it will follow the route defined in app.get BECAUSE IT WAS DECLARED FIRST and will return { d : "yay" }

Answer №4

When working with a POST request in nodejs, it is crucial to ensure there are no syntactical errors in the HTML file. According to feedback provided, after making modifications to the HTML code mentioned in the post, the issue was resolved and everything is now functioning properly.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Intro to Node and MongoDB</title>
    <link rel="stylesheet" href="">
</head>
<body>
<h1>Intro to Node and MongoDB</h1>
<form action="/addname" method="post">
    <input type="text" name="firstname" placeholder="FirstName">
    <input type="text" name="lastname" placeholder="LastName">
    <button type="submit">Add Value</button>
    
</form>
</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

What is the process for subtracting data from an object in a Node.JS environment?

My task involves analyzing sensor data which is stored as an array of objects containing current and previous month's information. The goal is to calculate the difference between the current and previous month's data and add this difference to th ...

Combining multiple API requests into a single call in a REST API

Consider this scenario: I have an API call http://localhost:3006/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb889e959fd6969e88889a9c9ec49e969a9297c69a9998bb968288928f9ed59894">[email protected]</a>&passw ...

Encountering a TypeError while attempting to install SASS using npm

Recently, I decided to delve into the world of Sass and wanted to install it on my system. Having Node.js already installed, I went ahead and typed in npm install -g sass Strangely, every time I try to check the version by typing sass --version, I keep en ...

Having trouble installing expo-cli in a React Native project

As someone who is new to react-native, I am in the process of trying to install expo-cli in order to create react-native apps. When running npm i -g expo-cli, a series of logs are returned: 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose cli ...

Adding information to an array within a document in a MongoDB database

I am facing an issue where I am trying to add data to the readBook array in my User collection document. The code and console.log seem to indicate that the User is retrieved from the database and there is data to push, but nothing changes after the code ex ...

Combining multiple NodeJS Express routes into a single route file for easier management

Currently, I am delving into the world of NodeJS as I work on a nodeJS API project. In order to manage different versions within my routes, I have structured my folders in the following way: application/ --app.js --routes/ ----V1/ ---- ...

Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far: ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Issues arising from the use of express and CORS

I have been working on a nodejs script using express, but I am facing issues with CROS requests even after following the documentation. I set up a web server to demonstrate the problem: Despite closely following the documentation, I can't seem to fig ...

The use of Buffer() is no longer recommended due to concerns regarding both security vulnerabilities and

I'm encountering an issue while trying to run a Discord bot. The code I'm using involves Buffer and it keeps generating errors specifically with this code snippet: const app = express(); app.get("/", (req,res) => { if((new Buffer(req.quer ...

Getting AJAX parameters from Angular in Node/Express Js

I am encountering an issue with my factory, which sends an ajax userId call to my node server. usersModel.getUser = function(userId){ return $http({ method: 'GET', url: 'http://localhost:3000/users/details', ...

Running Angular 2 build files with express.js: A step-by-step guide

Currently, I am trying to run index.html which is generated from an Angular2 app after using ng build. I attempted to use the following two lines of code individually, but unfortunately, neither of them worked for me: 1. app.use(express.static(path.resolv ...

Issue with ExpressJS: unable to send file from view configuration

I set up the views folder in my node app, but when I try to load an HTML file by passing just the file name, it's not working. Do I need to include the views config as well? (Am I missing something?) Can someone please provide me with some guidance o ...

Is it possible to create a React app (using create-react-app) paired with an Express backend all within a single

I am currently working on a React front-end application with an Express backend setup that is functioning smoothly in my local environment as a proxy API server. During development, the React front-end is hosted on port 3001 while the Express server is ru ...

The package 'models' imported from is not found [ERR_MODULE_NOT_FOUND] error

I'm currently in the process of setting up my project to utilize absolute imports. To accomplish this, I've made adjustments to my jsconfig.json file as shown below: { "compilerOptions": { "baseUrl": "./src&quo ...

What is the best way to send a request to an internal API using Express in a node.js application

In the past, I defined an API in this way. app.get('/login', function(req, res){ //Implementing the API }); Now, I have a new part of the API that requires using the login API for validation. app.get('/changePassword', function(req ...

Can a Node script execute package.json scripts?

Within my package.json file, I have multiple tasks defined in the "scripts" section: "scripts": { "test": "jest", "test:ci": "jest --runInBand --no-cache --watch false --coverage true", "test:codecov": "codecov", "tsc:check": "tsc --noEmit ...

Unable to find a solution for the dependency issue with google-maps-react

I recently attempted to clone a React project from GitHub for the first time. Here are the steps I followed: $ git clone <link> After cloning, I ran: npm install Unfortunately, I encountered an error related to google-maps-react. $ npm install --s ...

What steps do I need to take in order to execute `npm update -g npm` on Elastic Beanstalk?

Is there a way to automatically update the NPM version on my Elastic Beanstalk instances as they scale up, without having to manually shell into each one? I need a solution that can handle auto-scaling events and consistently ensure the latest version of ...

"Converting password encryption from sha1 in PHP to using the crypto module in

In PHP, I have these two functions: public function hashSSHA($password) { $salt = sha1(rand()); $salt = substr($salt, 0, 10); $encrypted_password = base64_encode(sha1($password . $salt, true).$salt); $hash = array("salt"=>$salt, "encryp ...