我想发送特定的参数和JSON API的所有条目作为响应.它显示Http_Header错误.怎么做呢?


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();
})

在for循环中使用res.send。来自get请求的数据只发送一次。与其在循环中使用res.send,不如使用to循环来push()向数组中添加元素,在循环后使用res.send来共享这个数组。

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();
})

相关内容

  • 没有找到相关文章

最新更新