简体   繁体   中英

unable to fetch from api

const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");

const app = express();

app.use(bodyParser.urlencoded({extended : true}));

app.listen(3000,function(){
    console.log("server is running");
})

app.get("/",function(req,res){
    res.sendFile(__dirname + "/index.html");
})

app.post("/",function(req,res){
    var url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?";
    var pincode = req.body.pinCode;
    url = url + "pincode=" + pincode;
    var date = req.body.date;
    url = url + "&date=" + date;
    console.log(pincode,date);
    
    request(url,function(err,res1,body){
        res.send(body.centers);
    })
})

for the above code (undefined) value is send in res.send(body.centers)

body is in json format given as below:

{"centers":[{"center_id":596215,"name":"MISSION UHC","address":"MISSION NADIAD","state_name":"Gujarat","district_name":"Kheda","block_name":"Nadiad","pincode":387002,"lat":22,"long":72,"from":"09:00:00","to":"18:00:00","fee_type":"Free"}

Try to see how body looks

request(url,function(err,res1,body) {
  console.log(body);
})

If body output in terminal with double quote like: { "key": "value" } that's mean body is JSON string and you need to parsing it to object with:

body = JSON.parse(body)

Then send it:

res.send(body.centers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM