在 Expressjs 中解析 application/x-www-form-urlencoded

Parsing application/x-www-form-urlencoded in Expressjs

我正在使用 Angular 到 POST 到我的 API。在处理 CORS 时,我将 header 设置为 www-form-urlencoded 以避免“pre-flight.

$http.post(url, {key1: value1, key2: value2},{"headers":{ "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }}).
  success(function(data, status, headers, config) {

  }).
  error(function(data, status, headers, config) {

  });

现在的问题是,我似乎无法解析正在 POST 编辑的 object,即使我的 server.js 中有这个,我认为它可以完成这项工作:

var bodyParser     = require('body-parser');
app.use( bodyParser.urlencoded({ extended: true }));

我正在尝试使用 req.body.key1 访问 POSTed 值,但我得到 undefined

您实际上并没有发送 application/x-www-form-urlencoded 数据,因此中间件变得混乱了。设置 Content-Type header 会告诉服务器您要发送哪种数据,但您实际上并没有在任何地方更改数据格式,因为没有任何内容告诉 Angular 您要发送urlencoded 数据,因此服务器仍在获取 JSON。

This answer 展示了如何对数据进行编码。