我正在尝试将json对象feedData
发送到服务器。该对象内部有一个File对象。
feedData = {
'title' : 'some title',
'type' : 1,
'feedBody' : {
'image' : File Object {lastModified : xxxx, name : 'image.jpg', type: 'image/jpg', ... }
}
}
return fetch(`/api/feeds/${feedId}/create`, {
method: 'POST',
body: JSON.stringify(feedData),
headers: {
'Authorization': getTokenHeader(token),
},
})
在我的路线中,
method: 'POST',
path: '/api/feeds/{feed}/create',
config: {
payload: {
output: 'stream',
parse: true,
allow: ['application/json', 'multipart/form-data', 'image/jpeg', 'application/pdf', 'application/x-www-form-urlencoded'],
maxBytes: 1024 * 1024 * 100,
timeout: false
},
handler: (req, res) => {
const params = { token: req.auth.token, ...req.params };
const payload = req.payload;
console.log('HAPI ', payload);
},
auth: {
strategy: 'jwt-strict',
mode: 'required'
}
}
我收到错误
http://localhost:3000/api/feeds/feed/create 415 (Unsupported Media Type)
我做错了什么?
答案 0 :(得分:10)
我进行了搜索,但找不到正确的答案。 我似乎很无奈。但是幸运的是,visua代码帮助调试了代码,我在index.js@hapi/subtext/lib文件中找到了这一行
if (contentType.mime === 'multipart/form-data') {
if (options.multipart === false) {// Defaults to true
throw Boom.unsupportedMediaType ();
}
return await internals.multipart (req, options, source, contentType);
}
然后我在路由器选项中修复了multipart = true:
{
payload: {
maxBytes: 1024 * 1024 * 100,
// timeout: false, // important
parse: true,
output: 'data',
allow: 'multipart / form-data',
multipart: true
}
}
成功了。感谢您的visua代码调试。我写信给可能会收到此错误的人。知道如何处理。
i使用hapi版本19.0.3
答案 1 :(得分:2)
这对我有用-
server.route({
handler: (request: any) =>
this.uploadProfileImage(request, profileService),
method: "POST",
options: {
auth: "false",
payload: {
maxBytes: 1024 * 1024 * 5,
multipart: {
output: "file"
},
parse: true
},
plugins: {
"hapi-swagger": {
payloadType: "form"
}
},
tags: ["api", this.controllerName],
validate: {
payload: Joi.object({
image: Joi.any().meta({ swaggerType: "file" })
})
}
},
path: `/api/${this.controllerName}/upload`
});
答案 2 :(得分:0)
以下方法有效,
在前端:-
const request = new XMLHttpRequest();
const formData = _getFileFormData(file);
request.open('POST', url);
request.setRequestHeader('authorization', getTokenHeader(token));
request.send(formData);
在后端:-
method: 'POST',
path: '/api/feeds/{feed}/create',
config: {
handler: function (req, res) {
const pre = preFilter(req.pre);
const token = req.auth.token;
const params = { ...req.params, ...pre.params, token: token };
const payload = req.payload;
return UploadAction.with(req, res).actionUploadToFeed(params, payload);
},
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data',
maxBytes: 1024 * 1024 * 100,
timeout: false,
},
validate: {
params: {
...FeedsController.getValidator(FeedsController.PARAM_CLIENT),
...FeedsController.getValidator(FeedsController.PARAM_FEED),
},
},
pre: [
...TransformParam.toLowerCase(FeedsController.PARAM_CLIENT),
...TransformParam.toLowerCase(FeedsController.PARAM_FEED),
],
auth: {
strategy: 'jwt-strict',
mode: 'required',
},
}