[英]Node.JS: Handling GET and POST request
I'm learning Node.JS and as practise I need to create to endpoints:我正在学习 Node.JS,作为实践,我需要创建端点:
My attempt is as follows:我的尝试如下:
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// Imports
const Album = require("./models/album");
const Purchase = require("./models/purchase");
// TODO code the API
// Connect to DB
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
console.log('database is connected successfully');
});
conn.on('disconnected',function(){
console.log('database is disconnected successfully');
})
conn.on('error', console.error.bind(console, 'connection error:'));
// Routes
app.get('/albums', function(req, res, next) {
Album.find({}, (err, albums) => {
if (!err) {
res.set({
'Content-Type': 'application/json',
'Status': 200,
})
return res.end(JSON.stringify(albums));
} else {
console.log('Failed to retrieve the Course List: ' + err);
}
});
});
// POST method route
app.post('/purchases', (req, res) => {
const purchase = new Purchase({
user: req.body.user,
album: req.body.album
})
purchase.save(function (err, post) {
if (err) { return err }
res.json(201, purchase);
})
})
module.exports = app;
Instructions for GET Request: GET 请求说明:
Since this is a JSON API, return JSON and a 200 status code, with the exception of destroy method which should return a 204 status code indicating no content.因为这是一个 JSON API,所以返回 JSON 和 200 状态码,除了 destroy 方法应该返回 204 状态码表示没有内容。
All three Album columns title, performer and cost should be returned in a data object for the GET, POST and PUT methods.应该在 GET、POST 和 PUT 方法的数据对象中返回所有三个专辑列标题、表演者和成本。 Here is an example of the format of response.body.data:
以下是 response.body.data 格式的示例:
Expected Form:预期形式:
response.body.data = {
_id: "the id of the album",
title: "Appetite for Destruction",
performer: "Guns N' Roses",
cost: 20
};
Instructions for POST Request: POST 请求的说明:
The POST /purchases route should expect user and album properties to be set in the request body. POST /purchases 路由应该期望在请求正文中设置用户和专辑属性。 It should then store a reference to both of these records on the newly created purchase record.
然后它应该在新创建的购买记录上存储对这两个记录的引用。
The response for POST /purchases should include the purchase record as well as the user and album relations, which should be populated with all their data fields. POST /purchases 的响应应包括购买记录以及用户和专辑关系,其中应填充其所有数据字段。
Album Schema:专辑架构:
const albumSchema = mongoose.Schema({
performer: String,
title: String,
cost: Number
});
Purchase Schema:购买模式:
const purchaseSchema = mongoose.Schema({
user: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
album: {type: mongoose.Schema.Types.ObjectId, ref: "Album"}
})
The program need to pass the follwing two test cases for these endpoints:程序需要为这些端点通过以下两个测试用例:
describe("GET /albums", () => {
it("should return an array of all models", async () => {
const album = new Album(albumData).save();
const res = await chai
.request(app)
.get("/albums")
;
expect(res.status).to.equal(200);
expect(res).to.be.json;
expect(res.body.data).to.be.a("array");
expect(res.body.data.length).to.equal(1);
expect(res.body.data[0].title).to.equal(albumData.title);
expect(res.body.data[0].performer).to.equal(albumData.performer);
expect(res.body.data[0].cost).to.equal(albumData.cost);
}).timeout(2000);
});
describe("POST /purchases", () => {
it("should create a new purchase and return its relations", async () => {
const otherAlbumData = {
title: "Sample",
performer: "Unknown",
cost: 2,
};
const album = await new Album(otherAlbumData).save();
const user = await new User({name: "James"}).save();
const res = await chai
.request(app)
.post("/purchases")
.send({user, album})
;
expect(res.status).to.equal(200);
expect(res).to.be.json;
expect(res.body.data).to.haveOwnProperty("user");
expect(res.body.data.user).to.haveOwnProperty("name");
expect(res.body.data).to.haveOwnProperty("album");
expect(res.body.data.album).to.haveOwnProperty("title");
expect(res.body.data.user.name).to.equal(user.name);
expect(res.body.data.album.title).to.equal(album.title);
}).timeout(2000);
});
});
The problem is that GET /albums doesn't properly fetch the data.问题是 GET /albums 没有正确获取数据。 Error: "expected undefined to be an array" while POST /purchases throws error 500, "Cannot read property 'user' of undefined" but as per description "route should expect user and album properties to be set in the request body".
错误:“预期未定义为数组”,而 POST /purchases 抛出错误 500,“无法读取未定义的属性 'user'”,但根据描述“路由应期望在请求正文中设置用户和专辑属性”。
Can somebody gives me a headsup?有人可以给我一个提示吗? I'm fairly new to Node.JS.
我对 Node.JS 还很陌生。 Thanks.
谢谢。
you should add following code before Routes
:您应该在
Routes
之前添加以下代码:
app.use(express.json({ limit: '15kb' }))
app.use(express.urlencoded({ extended: false }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.