2.8 KiB
2.8 KiB
id, challengeType, forumTopicId, localeTitle
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
587d7fb2367417b2b2512bf7 | 2 | 301520 | 使用 body-parser 来解析POST请求 |
Description
POST /path/subpath HTTP/1.0
From: john@example.com
User-Agent: someBrowser/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 20
name=John+Doe&age=25
正如你所看到的,正文被编码成了查询字符串。这是 HTML 表单使用的默认格式。使用 Ajax,我们还可以使用 JSON 来处理具有更复杂结构的数据。还有另一种类型的编码:multipart/form-data。它用来上传二进制文件。 在本练习中,我们将使用网址编码 body。要解析来自 POST 请求的数据,你必须安装一个包:body-parser。这个包允许你使用一套可以解码不同格式数据的中间件,在这里查看文档。
Instructions
bodyParser.urlencoded({extended: false})
方法。extended=false
是一个配置选项,告诉解析器使用经典编码。当你使用它时,值只能是字符串或者数组。继承版使用起来数据更加灵活,它比 JSON 更好。传递给app.use()
上一次方法调用返回的函数。通常中间件必须挂载在所有需要它的路由之前。
Tests
tests:
- text: '"body-parser" 中间件应该被挂载'
testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/add-body-parser'').then(data => { assert.isAbove(data.mountedAt, 0, ''"body-parser" is not mounted correctly'') }, xhr => { throw new Error(xhr.responseText); })'
Challenge Seed
Solution
/**
Backend challenges don't need solutions,
because they would need to be tested against a full working project.
Please check our contributing guidelines to learn more.
*/