Home > Software design >  pass array to backend
pass array to backend

Time:11-13

Here i am trying to pass array to my backend (Node.js/Express). I want to change my type of "arr" to Array but its showing the "objects". I tried Object.enteries/keys/values but couldn't able to change it.

const K_Way_Merge_Sort = async ({
    array,
    setArray,
    setColorsArray,
    visualizationSpeed,
} = {}) => {
    var JSONObject = JSON.parse(JSON.stringify(array));
    axios.post(
        'http://localhost:5000/k_way_external_merge_sort',
        {JSONObject}
        , ((data) => {
            console.log(data);
        }))
        .catch((err) => {
            console.log(err)
        })
}

export default K_Way_Merge_Sort

My Backend File is

const express = require('express');
const bodyParser = require("body-parser");
const fs = require('fs')
const { readFileSync, promises: fsPromises } = require('fs');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true }));
const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true,       
    optionSuccessStatus: 200
}
app.use(cors(corsOptions));

function WriteFiles(array){
    var file = fs.createWriteStream('text/input.txt');
    for (let i = 0; i < array.length; i  ) {
        file.write(array[i]   '\n')
    }
    file.end();
}

app.post('/k_way_external_merge_sort',(req,res) => {
    let array = req.body.JSONObject;
    const arr = Object.values(array);
    res.send('done');
})

app.listen(5000,() => {
    console.log('running');
})

CodePudding user response:

In Javascript, typeof an array instance is actually an 'object'. If you so want, you can still test if it's an array with arrayInstance instanceof Array, or you might want to consider Array.isArray() method; other possiblities are mentionned in this post.

  • Related