第一次尝试 node 和 express。我使用 get 和 post 的例子,我需要介绍 DELETE 删除基于标题的书,我是另一个 GET,以便在键入“localhost:3000 / books”时显示所有书籍。
这是我到目前为止
var express = require('express');
var app = express();
var bodyPr = require("body-pr");
const { fstat } = require('fs');
// adding a body pr to handle JSON and url encoded form data for us automagically
app.use(bodyPr.json());
app.use(bodyPr.urlencoded({ extended: false }));
// our in-memory fake data store is just an array of javascript objects
var books = [
{ "author": "me", "title": "BookA", "pages": 600, "quality": "new" },
{ "author": "you", "title": "BookB", "pages": 400, "quality": "used" },
{ "author": "us", "title": "BookC", "pages": 500, "quality": "old" },
];
// request handler to search based on two fields: author and title
app.get('/book', function (req, res) {
// get the query params
var title = req.query.title;
// initialize the return data
var data;
// search for the book
for (var i = 0; i < books.length; i++) {
if (books[i].title == title) {
data = books[i];
break;
}
}
// pass JSON back to client
res.set('Content-type', 'application/json');
res.status(200);
res.send({"book": data});
});
// post handler to add a book to the hardcoded list
// this is definitely not the correct model for storing data
// this is simply an example
app.post('/book', function (req, res) {
// access the request POST body from the request object
var data = req.body.data;
// add the new book to the data store and return it
var book = {
"author": req.body.author,
"title": req.body.title,
"pages": req.body.pages,
"quality": req.body.quality,
}
// add the book to the hardcoded list of books
books.push(book);
// return JSON list of books
res.set('Content-type', 'application/json');
res.status(201);
res.send({"books": books});
});
// listen for HTTP requests on port 3000
app.listen(3000, function() {
console.log("listening on port 3000");
});
我有这个删除只是不知道它是否会工作。我现在还在玩邮差
// delete
app.delete('/delete/:booke', function(req, res) {
var id = req.params.book;
fstat.readFile("./book.json", 'utf8', (err,data) => {
data = JSON.p( data );
delete data["book" + title];
console.log( JSON.stringify(data) );
res.status(200);
return res.send("Book removed");
});
})
任何帮助将是巨大的。
不要对数组使用delete
关键字,它只会清空元素,同时保留相同的数组长度。
此外,您希望从books
中删除,而不是从data
中删除。
如果booke
URL 段(其中有一个错字)应该包含要删除的索引,则代码为:
books.splice(id, 1);
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(46条)