我有一个角度应用程序,并且表达服务器是一个调用外部API的中间件
$scope.uploadLayout = function(){
$scope.selectedTemplate.selected = $scope.items;
var fd = new FormData()
fd.append('name', $scope.template.name)
fd.append('description', $scope.template.desc)
fd.append('file', $scope.template.file)
$http.post('/layout/template',fd,{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined}
}).then(function(response){
getLayoutRules()
console.log("file uploaded successfully")
})//add error callback
console.log('test')
}
当express将数据发送到外部API时,会出现主要问题
app.post('/layout/template', upload.any(), (req, res) => {
// console.log(req.body.name);
var formdata = new Buffer(req.files)
var form = new FormData();
form.append('name', req.body.name)
form.append('description', req.body.description)
form.append('file', formdata)
console.log(form)
var contentLength = req.files.length;
var url = `${apiUrl}/layout/template`
// var r = request.post(url,{
// headers: { 'Content-Type': undefined}
// }, function optionalCallback(err, httpResponse, body) {
// if (err) {
// return console.error('upload failed:', err);
// }
// console.log('Upload successful! Server responded with:', body);
// })
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'multipart/form-data'
},
url:url,
method:'POST',
body: form
},function(err,body,res){
console.log(err)
console.log(body)
})
});
我已检查表单是否正常生成但外部API服务器错误地说明了
“请求被拒绝,因为没有找到多部分边界”
请帮助,或者还有其他方法吗?
更新
我稍微修改了代码以发送从浏览器中提取的请求标题
app.post('/layout/template', upload.any(), (req, res) => {
var header = req.headers['content-type']
var formdata = new Buffer(req.files)
console.log(formdata)
var fd = new FormData();
fd.append('name', req.body.name)
fd.append('description', req.body.description)
fd.append('file', formdata)
//var contentLength = req.files.length;
//console.log(contentLength)
var url = `${apiUrl}/layout/template`
//console.log(fd)
// var r = request.post(url,{
// headers: { 'Content-Type': undefined}
// }, function optionalCallback(err, httpResponse, body) {
// if (err) {
// return console.error('upload failed:', err);
// }
// console.log('Upload successful! Server responded with:', body);
// })
request({
headers: {
'Content-Type': header
},
url:url,
method:'POST',
body: fd
},function(err,body,res){
//console.log(body)
console.log(res)
})
//console.log(request)
});
所以现在我发送的是浏览器设置的相同边界,但现在java服务器没有检测到表单参数