Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you.

My project involves creating a web application for a check-in/check-out system where scanning a barcode automatically populates information into a Google spreadsheet.

const express = require('express');
const app = express();
const fs = require('fs');
const GoogleSpreadsheet = require('google-spreadsheet');
const creds = require('./client_secret.json');

app.use(express.static('public'));

app.get('/', function (req, res) {
    const contents = fs.readFileSync('views/welcome.html').toString();
    res.send(contents);
});

app.get('/info', function (req, res) {
    res.send('Hello Info!');
});

app.get '/checkin', function (req, res) {
    const contents = fs.readFileSync('views/no.html').toString();
    res.send(contents);
    console.log("checking in");
    console.log(req);
});

app.get('/checkout', function (req, res) {
    const contents = fs.readFileSync('views/no.html').toString();
    res.send(contents);
    console.log("checking out");
});

app.post('/checkin', function (req, res) {
    console.log("posting check-in info");

    // Extract data from POST request here
    // Send data to Google Sheets

    // Authenticate with Google Spreadsheets API using service account credentials
    const doc = new GoogleSpreadsheet(________);

    doc.useServiceAccountAuth(creds, function (err) {
        doc.getInfo(function(err, info) {
            console.log('Loaded doc: '+info.title+' by '+info.author.email);
            const sheet = info.worksheets[0];
            console.log('Sheet 1: '+sheet.title+' '+sheet.rowCount+'x'+sheet.colCount);
        });
    });

    // Consider client confirmation here
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});

Answer №1

If you want to retrieve POST data, you will need to install the body-parser package.

Firstly, import it:

var bodyParser = require('body-parser');

Then, you can use it by adding this line of code:

app.use(bodyParser.urlencoded({ extended: false }))

Finally, in your middleware function, you can access the data like this:

var ID = req.body.ID;

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

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Changing a zero-prefixed string into JSON format using Swift 4

When attempting to encode an integer that starts with a 0 into JSON using swift 4, I encountered an issue. Even though I am utilizing a standard JSONSerialization library, I am facing difficulties in serializing the data after converting the string to utf ...

What sets apart the JavaScript console from simply right-clicking the browser and opting for the inspect option?

As I work on developing an angular application, one of my tasks involves viewing the scope in the console. To do this, I usually enter the code angular.element($0).scope(). This method works perfectly fine when I access the console by right-clicking on th ...

A guide to displaying the date retrieved from a JSON data file API request using JavaScript

How can I display the date from a JSON data file API call using JavaScript? I am facing difficulty in showing the date on the dashboard display page. I am utilizing JavaScript with async-await for calling the API, and Bootstrap 4 for design. The function ...

Creating specifications for query parameters in Loopback that are essential for handling CRUD operations

Our journey with Loopback has been successful thus far, but we are now looking to enhance our API documentation by including query parameters. In the swagger.json file, there could be a section that resembles this: { "swagger": "2.0", "i ...

Creating a GWT-compatible solution for implementing the Google Visualization - Annotation Chart

I am currently using the newly launched Annotation Chart in GWT by integrating native JavaScript. I have managed to display the example chart successfully, but unfortunately, it lacks interactivity and behaves more like an image. Can anyone provide guidanc ...

Vibrant array of colors in AmCharts' line graphs

I'm looking to enhance my graph by having lines between the bullets in different colors based on their direction. For instance, if a line is rising (going from a bullet of smaller value to greater value), it should be green; if a line is falling, it s ...

Prevent EACCES issues with npm/node when using Ubuntu?

Setting up the system environment $ lsb_release -a 2> /dev/null | grep Desc Description: Ubuntu 14.04.1 LTS $ sudo apt-get install build-essential $ sudo add-apt-repository ppa:chris-lea/node.js && sudo apt-get update $ sudo apt-get install ...

How to tailor the output of $group aggregation in node.js

When using aggregate in node.js, my code looks like this: collection.aggregate( { $group : { _id : "$id_page", "count" : {$sum : 1} } }, {$sort : {"count" : -1}}, {$limit : 1} ).limit(1).toArray(f ...

"Is it possible to conditionally render a component depending on the state in

One of the challenges I'm facing is customizing a filter icon from MaterialUI. My goal is to change its color to black when a checkmark is checked, and adjust its position accordingly. Additionally, when a box is checked, it should fill in setFilters. ...

Building a Dynamic Web App with PHP and Vue.js

I developed an API using PHP and you can access it through this link: However, I encountered an issue when trying to display the data on the front-end of my Vue.js (Home.vue) file using axios. Below is the code I used: <ul class="ta-track-list" v-if= ...

Does adding the async attribute to a script impact the timing of the onload event?

I am facing an issue with a webpage that contains a script tag in the HEAD section: <script src="somescript.js" type="text/javascript" async></script> Since it has the async attribute, this script loads asynchronously, allowing the browser to ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...

"Encountered an issue while trying to find the Node.js installation directory" error message appeared during npm install

Every time I try to run npm install or install anything using Node (like nvm) in any terminal (or even within Visual Studio Code), I encounter a consistent error message: node:net:404 err = this._handle.open(fd); ^ Error: EISDIR ...

Create a script that will split a single block of text into separate sections based on predefined conditions

I have developed a script using Tampermonkey which modifies a value on a specific webpage. On the webpage, there is an input box with the value "FPPUTHP1100000". This value is a material code with the following structure: F represents FRESH PPUTHP repr ...

Algorithm for Filling Tiles in a Gaming Environment

Background: In my current project, I'm developing a unique tile-based game in Javascript. The game involves a character who can freely move around the map without taking diagonal paths - only left, right, up, or down movements are allowed. As the cha ...

Tips for determining the duration between the Monday of last week and the Sunday of last week

Can anyone help me figure out how to retrieve the dates from last week's Monday to last week's Sunday using JavaScript? I've searched through various sources with no luck. Hoping someone here can provide some guidance. ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...