Express URL param issues with Nested array in NodeJS

I'm having an issue getting data out of an array I'm sending to my API via an AXIOS call to Express. The call sends just fine, but I provide it below. The request is received fine and all other data in the request inserts to the database with no issue. The problem is I can't get at the data in the property_features param that is being sent. I see in the call I'm getting multiple property_features params but I can't figure out how to get the data.

console.log('Logging Features' + params.property_features);

shows undefined but the query in the console shows I got the data.

app.all('/', function(req, res) {
    var querystring = url.parse(req.url, true);
    var params = querystring.query;
    //console.log(querystring.search);
    console.log('Logging Features' + params.property_features);
    //Insert Type to populate new property Type field
    if (params.acc === 'ant') {
        console.log('Creating new property type...');
        connection.query('INSERT INTO property_type(types) VALUES(?)', [params.property_type], function(error, results, fields) {
            if (error) throw error;
            console.log('Insert Property Type Query Successful' + results);
        });
        res.send('Property type added OK!!');
        //Insert Property
    } else if (params.acc === 'cnp') {
        console.log('Creating new property....');
        params.property_id = newuuid();
        connection.query('INSERT INTO properties(property_id, branch, reference_number, property_type, property_price, price_option, rooms, bath, date_built, squarefeet, address, location, zip, rental_criteria, short_descrip, full_descrip, property_status, featured, visible, tour_url, property_features, notes) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [params.property_id, params.branch, params.reference_number, params.property_type, params.property_price, params.price_option, params.rooms, params.bath, params.date_built, params.squarefeet, params.address, params.location, params.zip, params.rental_criteria, params.short_descrip, params.full_descrip, params.property_status, params.featured, params.visible, params.tour_url, params.property_features, params.property_notes], function(error, results, fields) {
            if (error) throw error;
            console.log('Insert Property Query Successful' + results);
        });
        res.send('Property added OK!!');
        //Insert location to populate new property locations field
    }
    console.log('There was a successful transaction!!!!');
});

So as you can see I'm recieving a request with params and parsing them then inserting them into the database via that mysql module in nodejs. Some others as well but I'm pretty sure this is isolated to that module.

The issue I'm running into is with the property_features param.

cp = {
    property_id: '',
    branch: document.getElementById('prop_branch').value,
    reference_number: document.getElementById('reference_number').value,
    property_type: document.getElementById('property_type').value,
    property_price: document.getElementById('property_price').value,
    price_option: document.getElementById('price_option').value,
    rooms: document.getElementById('rooms').value,
    bath: document.getElementById('bath').value,
    date_built: document.getElementById('date_built').value,
    squarefeet: document.getElementById('squarefeet').value,
    address: document.getElementById('property_address').value,
    location: document.getElementById('property_location').value,
    zip: document.getElementById('property_zip').value,
    rental_criteria: document.getElementById('rental_criteria').value,
    short_descrip: document.getElementById('short_descrip').value,
    full_descrip: document.getElementById('full_descrip').value,
    property_status: document.getElementById('property_status').value,
    featured: '',
    visible: '',
    tour_url: document.getElementById('tour_url').value,
    property_notes: '',
    property_features: []
};

This is an example of the data that is being sent via the http request to express using Axios. That side of the relationship works just fine because I'm getting the data in my API.

2018-10-19 16:41:05.776 PDT "GET /?acc=cnp&branch=Branch&reference_number=&property_type=Unfurnished&property_price=&price_option=Per+Month&rooms=1&bath=0&date_built=&squarefeet=&address=&location=Long+Beach&zip=&rental_criteria=&short_descrip=&full_descrip=&property_status=Leased&featured=true&visible=true&tour_url=&property_notes=&property_features%5B%5D=Swimming+Pool&property_features%5B%5D=Close+to+Burbank+Elementary&property_features%5B%5D=Lower+Unit&property_features%5B%5D=Laminated+Hardwood+Floors&property_features%5B%5D=Utilities+paid HTTP/1.1" 304 158 - "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" "centprop-219008.appspot.com" ms=1117 cpu_ms=1274 cpm_usd=1.7657e-8 loading_request=1 instance=00c61b117cf1a1e2d4a42d33a8f29b82f4343c86edd94138399fa3b2d077916b3324cd9246 app_engine_release=1.9.65 trace_id=43a2aabf9b0d5726a3dfb4ba610b5ba2

As you can see I'm sending my data in a JSON format with an embedded array. That is where my problems happen. All other data populates in the database just fine except the data in this variable.

axios.get(theUrl, {
    params: {
        acc: 'cnp',
        property_id: cp.id,
        branch: cp.branch,
        reference_number: cp.reference_number,
        property_type: cp.property_type,
        property_price: cp.property_price,
        price_option: cp.price_option,
        rooms: cp.rooms,
        bath: cp.bath,
        date_built: cp.date_built,
        squarefeet: cp.squarefeet,
        address: cp.address,
        location: cp.location,
        zip: cp.zip,
        rental_criteria: cp.rental_criteria,
        short_descrip: cp.short_descrip,
        full_descrip: cp.full_descrip,
        property_status: cp.property_status,
        featured: cp.featured,
        visible: cp.visible,
        tour_url: cp.tour_url,
        property_notes: cp.property_notes,
        property_features: cp.property_features
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
})
.then(function () {
    // always executed
});

Here is the axios call that sends the data, again this side works fine and the data does get to the API I'm posting this this for clarity.

2018-10-19 16:43:12.842 PDT Logging Features undefined

This is the problem I'm having when I log the param out in the API. The features parameter is getting multiple pieces of data so in the request I see property_feature=&!!! many times.

Again I tried parsing the data and stringify and I'm not able to manipulate the data in that call. I feel like I'm missing an address to an array layer I can't get my head around.

Modules I'm using.

const http = require('http');
const url = require('url');
const mysql = require('mysql');
const config = require('./config');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const axios = require('axios');
const querystring = require('querystring');
const uuid4 = require('uuid4');
const app = express();
const admin = express(); // the sub app
const secret = express();
const port = 8080
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Thanks in advance for the help.

Answers:

Answer

You are using querystring incorrectly to get the url parameters.

First of all you have a local variable named querystring which conflicts with the node module variable. I am not sure why you aren't getting an error there, since you used const for the node module querystring.

Anyway, the correct way to parse the parameters is:

const querystring = require("querystring");
var params = querystring.parse(req.url);
console.log(params.property_features);

This should also handle the case where you have multiple property_features variables in your url, by placing them in an array.

Answer

Fixed. So I was being a noob. I found the issue in the place I thought it wasn't, the original Axios call.

When creating that call I used the below format to setup my data which works fine until you get to the array.

cp = {
property_id: '',
property_notes: '',
property_features: []
};

I was pushing data into the array.

    for (i = 0; i < active.length; i++) {
    curfea.push(active[i].id);
    }

And when I made the Axios call I was running into issues. It would send the data as a string but all other data would be fine. That's when I realized I was dealing with an Axios object and so my thinking of how the data would transmit was wrong.

    async function creaprop() {
    console.log('Creating Property.......');
    try {
        const propfeatures = await axios(theUrl, { params: {
            acc: 'cnp',
            property_features: JSON.stringify(curfea),
            property_notes: scp.property_notes
        } });
        console.log('Async Request: Add New Property');
    } catch (error) {
        console.error(error);
    }
   }

Running a simple stringify on the data prior to sending it fixed all of my problems. I was having an object issue not an Express or parameter issue.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.