Retrieve information from a URL using an Express API

Every 45 minutes, my API receives a request:

GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}

I need to extract {device}, {data}, {time}, and {customData#trama} from the URL and store them in separate variables. This data is in hexadecimal format and I want to parse it into readable values, then insert it into my database. How can I retrieve these values from the URL?

Additionally, I have a question about req, res. I understand that res is for responding to the client, but I'm not sure how req works. I'm new to this and would appreciate some guidance.

Below is the code for my API. I've tested it with Postman and it's working correctly:

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
    user: "mgr@stanpgtest",
    host: "stanpgtest.postgres.database.azure.com",
    database: "my db name",
    password: "my pass",
    port: 5432
});

const app = express();
app.use(cors());
app.use(bodyParser.json());

app.listen(8000, () => {
    console.log(`Server is running, listening to port 8000`);
});

app.post("mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}", (req, res) => {
    const { label, status, priority } = req.body;
    pool.query(
        "select now()",
        (error, results) => {
            if (error) {
              throw error;
            }
            res.send(results);
        }
    );
});

Answer №1

In order to retrieve your parameters from the request object, you will need to define the path in a specific format as shown below:

app.post("readings/sigfox_devices/:device/:value/:timestamp/:extraData", (req, res) => {
   const {device, value, timestamp, extraData} = req.params
}

It appears that the use of #trama in the route pattern is not supported, so you may need to find an alternative approach.

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

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

What is the process for incorporating synchronous tasks within an asynchronous function?

const fs = require('fs') const readline = require('readline') const stream = require('stream') const rl = readline.createInterface({ input: fs.createReadStream('logs.txt') }) var uniqueItems = new Set() // ASY ...

Tips for embedding an object into an iframe source

I have successfully integrated a YouTube iframe into my HTML file. However, I would like the source URL to be dynamically generated based on data from the backend rather than manually inputting the URL as shown below. In the admin panel, there is an object ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

Angular user profile update button not functioning as expected

We are currently implementing Angular alongside Node.js Express. Our issue arises when attempting to update user details from the settings page, as clicking the update button triggers the following error: Failed to load resource: net::ERR_CONNECTION_RESET ...

Utilizing NodeSize to Optimize the Spacing Among Nodes in the D3 Tree Arr

Currently, I am trying to adjust the positioning of my rectangle nodes because they are overlapping, as illustrated in the image below: In my research, I discovered that D3 provides a nodeSize and separation method. However, I encountered difficulties imp ...

I am unable to display the service response in the Angular component

I'm facing an issue with displaying data in an angular component from a service. The process from the service to the component seems fine, but when I try to use the variable in HTML, it doesn't show the result. For this project, I am using the M ...

Creating a Redirect Form that Directs Users to a Specific Page Depending on Input Data

Apologies if this is a basic issue, but I'm struggling to figure it out. I am trying to create a form field on a webpage that will redirect users to a specific page based on the data they input. For example, if someone types in "dave" and submits the ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

Issue: The code mentioned below is functioning perfectly during development, but once it is deployed on Heroku, it exhibits sporadic behavior

Struggling to make socket.io function properly on Heroku, encountering issues with code inconsistency between development and deployment. The problem persists even after uploading to Heroku: 1. No unusual activity in the logs. 2. Data saved to the databa ...

Node.js: Crafting appropriate responses for errors in asynchronous operations or promises

Looking for a simple solution to handle all async/Promise errors effectively? The typical pattern of: app.use(function (err, req, res, next) { ... }); does not cover async errors and the search for an alternative has been challenging. I came across a ...

Adding Image Files to a Ruby on Rails JSON API using Carrierwave

My Ruby on Rails JSON API is designed to handle HTTP requests with both JSON data and files in a single request. To accomplish this, I integrated the Carrierwave gem. When initiating a request with Python, the code snippet looks like this: url = [...] hea ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...

Unable to display items in controller with AngularJS

I am facing an issue with displaying a slider using ng-repeat in my AngularJS code. The pictures and other elements defined in the controller are not showing up on the page. Here is the JavaScript code snippet: angular.module('starter', []) .co ...

Is there a JavaScript function available to remove comments from previously commented HTML code?

<div id="div1">bar</div> JQuery function addComment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } addComment($('#div1')); Looking for assistance in unc ...

Node.js Swagger Router is redirecting to multiple routes simultaneously

Currently, I am utilizing https://github.com/apigee-127/swagger-tools for managing swagger documentation on my server. On top of that, I have a client with a proxy route to the server in a way that when I access http://{client_url}/server, it redirects me ...

Is it possible to have Vue.js code within a v-for loop in such a way that it executes every time the v-for loop runs?

<div class="questions" v-for="(q,index) in questions " :key="index" {{this.idx+=1}} > <h3 > {{q.content}}</h3> <h3> A) {{q.a}} </h3> <h3> B) {q.b}} </h3> ...