文件上传请求全部返回400状态代码

时间:2018-01-28 04:10:11

标签: javascript express file-upload multipartform-data

我正在尝试使用Express进行文件上传,但我发送的每个get(endpoint) { return this.request('GET', endpoint, null); } post(endpoint, body) { return this.request('POST', endpoint, body); } postFile(endpoint, file) { return this.request('POST', endpoint, file, contentTypes.file); } async request(method, endpoint, body, contentType=contentTypes.json) { const { authToken } = this; const endpointUrl = this.getEndpointUrl(endpoint); const headers = new Headers(); if(authToken) { headers.append(authTokenHeader, authToken); } headers.append('Accept', 'application/json, application/xml, text/plain, text/html, *.*'); headers.append('Content-Type', contentType); const response = await fetch(endpointUrl, { method: method, headers: headers, body: this._serializeRequestBody(body, contentType), }); const result = await this._parseResponse(response); if(!response.ok) { if(response.status === 401) { this.revokeAuth(); } throw result || new Error('Unknown error (no error in server response)'); } else if(result && result.authToken) { this.setAuthToken(result.authToken); } return result; } 请求都会收到400错误的请求响应而没有错误。只是一个空对象。我目前正在使用busboy-body-parser来解析多部分formdata请求,但我也尝试了express-fileupload并遇到了完全相同的问题。

以下是我的请求方法:

_serializeRequestBody

以下是_parseResponse_parseResponse(response) { const contentType = response.headers.get('Content-Type').split(';')[0]; if(contentType === contentTypes.json) { return response.json(); } return response.text(); } _serializeRequestBody(body, contentType) { if(!body) return null; switch(contentType) { case contentTypes.json: return JSON.stringify(body); case contentTypes.file: const formData = new FormData(); formData.append('file', body); return formData; } return body; }

contentTypes

const contentTypes = { json: 'application/json', file: 'multipart/form-data', };

if(this._expressLoggingMiddleware) {
  app.use(this._expressLoggingMiddleware);
}

if(this.isNotProductionEnv && this.isNotTestEnv) {
  app.use(require('morgan')('dev'));
}

// Adds `res.success` and `res.fail` utility methods.
app.use(require('./utils/envelopeMiddleware')());

// Allow cross-origin requests if `config.cors` is `true`.
if(config.cors) app.use(require('cors')());

// Parse JSON and form request bodies.
app.use(busboyBodyParser()); // parses multipart form data (used for file uploads)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Lookup users by the JWT in their request header.
app.use(passportJWTMiddleware(passport, this.jwtSecret, jwtPayload =>
  this.lookupUserfromAuthToken(jwtPayload).catch((error) => {
    log.warn('Error while looking up user from JWT:', error);
    return null;
  })
));

// Serve files from `config.publicDir`.
if(config.publicDir) {
  log.debug(`Hosting static files in "${config.publicDir}"`);
  app.use(express.static(config.publicDir));
}

我的快速中间件:

npx browser-sync start --server src/ --files 'src/*.html' 'src/css/*.css' 'src/js/*.js'

以下是Chrome开发工具中的请求信息

Chrome dev tools request information

请求有效负载:

Chrome dev tools request payload

回复:

Chrome dev tools response

1 个答案:

答案 0 :(得分:0)

答案最终是:不要手动将Content-Type标题设置为multipart/form-data,因为如果您让浏览器为您执行此操作,它还将针对所需{{1}值内容类型。

因此,为了修复我的代码,我只需要在发送JSON时显式设置boundary标头:

Content-Type