我实际上正在使用文件上传和一些数据开发Angular webform。 以下是请求标头:
POST /tests/add HTTP/1.1
Host: localhost:3000
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Content-Type: application/json;charset=utf-8
Referer: http://localhost:8000/
Content-Length: 2033
我以这种方式构建请求:
var formData = new FormData();
formData.append('file', $scope.test.file);
$http({
method: 'POST',
url: backUrl + '/tests/add',
data: { 'file': $scope.file,
'token': 'test'},
contentType: false,
processData: false,
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
但它始终返回400错误请求,并显示以下错误:
Unexpected token -
400
SyntaxError: Unexpected token -
at parse (/home/me/projects/www/node_modules/body-parser/lib/types/json.js:83:15)
at /home/me/projects/www/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/home/me/projects/www/node_modules/raw-body/index.js:262:16)
at done (/home/me/projects/www/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/home/me/projects/www/node_modules/raw-body/index.js:307:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
这是我在后端对bodyParser的唯一引用:
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
defer: true
}));
我做错了什么?
答案 0 :(得分:4)
你是否肯定要发送JSON?
很可能你使用的是无效的JSON,它会强制使用bodyParser.json()。
确保您使用的是有效的JSON。您还可以将bodyParser.json与bodyParser.raw交换为中间件。