0

我有一个有角度的应用程序,并表示服务器是一个调用外部 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 服务器未检测到表单参数

4

0 回答 0