I want to send specific parameters and all entries of json api as a respone. It is showing Http_Header error. How to do it?

Viewed 24

const fetch = require("node-fetch");

const express = require('express');

const app = express();

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/todoApi');

mongoose.connection.on('error', e=>{

console.log('connection failed');

});

mongoose.connection.on('connected', connected=>{

console.log('connection successful to the database');

});

const todoSchema = new mongoose.Schema({

userId:{
    type: Number,
},
id:{
    type: Number
},
title:{
    type: String
},
completed:{
    type:Boolean
}

});

const todoModel = mongoose.model("todoModel", todoSchema);

app.get("/todo", (request, res)=>{
    async function getToDo(){
        const todoData = await fetch('https://jsonplaceholder.typicode.com/todos');
        const response = await todoData.json();
        for(let i = 0; i<response.length;i++){
            let kuchbhi;
            const todos = new todoModel({
                userId: response[i]["userId"],
                id: response[i]["id"],
                title: response[i]["title"],
                completed: response[i]["completed"]  
            })
            res.send(response[i]);
        }
        console.log(response[0]['userId']);
    }
    getToDo();

})

1 Answers

you are using res.send inside for loop. The data from get request is sent only one time. Instead of using res.send inside loop, use to loop to push() to add elements in the array, use res.send after the loop to share this array.

app.get("/todo", (request, res)=>{
async function getToDo(){
    const todoData = await fetch('https://jsonplaceholder.typicode.com/todos');
    const response = await todoData.json();
    let responseArray = [];
    for(let i = 0; i<response.length;i++){
        let kuchbhi;
        const todos = new todoModel({
            userId: response[i]["userId"],
            id: response[i]["id"],
            title: response[i]["title"],
            completed: response[i]["completed"]  
        })
        responseArray.push(response[i]);
    }
    res.send(responseArray);
}
getToDo();
})
Related