简体   繁体   中英

How to display a single value from restful API using Express in Javascript

Here i want to get the prices of the "id" that i pass through URL.

const express = require("express");
const app = express();
app.use(express.json());

let cars = [{
  id: 1,
  name: "cultus",
  price: 15000,
  color: "gray",
},
{
 id: 2,
 name: "corolla",
 price: 50000,
 color: "golden",
},
{
 id: 3,
 name: "mercedes",
 price: 100000,
 color: "black",
}
];

 app.get("/", function (req, res) {
 res.send("Hello World");
});

 app.get("/api/cars", function (req, res) {
 res.send(cars);
})

app.get("/api/cars/:id", (req, res) => {
let car = cars.find(c => c.id=== parseInt(req.params.id));

if (!car) return res.status(400).send("Product not found");
return res.send(car);
})

app.listen(3000);

What i want is that if i pass "id=1" in URL then only the price of that record should be displayed. And how to display all cars having price greater than the price passed through URL.

You can pass the price only using

app.get("/api/cars/:id", (req, res) => {
let car = cars.find(c => c.id=== parseInt(req.params.id));
    
if (!car) return res.status(400).send("Product not found");
// only send price
return res.send({price: car.price});
})

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