发送多部分数据时出错代码500

时间:2016-07-27 22:42:44

标签: node.js swift express alamofire multer

我正在使用Alamofire将多部分数据发送到我的Nodejs和Express API。我正在使用Multer上传图像文件和一些文本参数。出于某种原因,我可以上传图片文件,但我无法发送文字,例如" title"," price"和" description" - 当我尝试从Swift应用程序上传时,这可能是我继续收到500错误代码的原因。我不确定是什么问题。我究竟做错了什么?这是我的快车路线:

var multer = require('multer');
var upload = multer({ dest: 'public/uploads/'})

var app = express();

app.use(function(err, req, res, next) {
    console.log(err);
    next(err);
});

var server = app.listen(3000, () => {
  console.log('listening on *:3000');
});


app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// get request params
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


// log to console
app.use(morgan('dev'));


app.use(express.static('public'));


// use passport package in app
app.use(passport.initialize());
app.use(passport.session());


app.use(multer({dest:'./uploads/'}).single('images'));


/*
app.get('/', function(req, res) {
  res.send('Hello! Welcome to the land of dragons!');
})
*/


// pass passport for config
require('./config/passport')(passport);




// create new product
app.post('/newproduct', upload.single('images'), function (req, res) {

   if (req.body.title == '' || req.body.price == '') {
    res.json({success: false, msg: 'Please add title and price.'});
    console.log('title: ' + req.body.title);
    console.log('price: ' + req.body.price);
  } else {

    var newProduct = new Product({
     title: req.body.title,
     price: req.body.price,
     description: req.body.description,
     images: req.file

    });


    console.log(req.body);
    console.log(req.file);

    // save the new product
    newProduct.save(function(err) {
      if (err) {
       res.json({success: false, msg: 'Listing was unsuccessful.'});
      } else {
       res.json({success: true, msg: 'Successful creating a new product!'});
       console.log(newProduct.createdAt);
       console.log(newProduct.updatedAt);
      }

    });

  }

});

当我尝试在Postman中发出POST请求时,它会给我错误信息"列表不成功。"因为保存对象需要标题和价格。

这就是我在终端中得到的结果:

    {}
{ fieldname: 'images',
  originalname: 'Screen Shot 2016-07-27 at 2.48.14 PM.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: './uploads/',
  filename: 'b3247d2b48591c1d6e47f5413647979b',
  path: 'uploads/b3247d2b48591c1d6e47f5413647979b',
  size: 285034 }
POST /newproduct 200 14.081 ms - 51

当我尝试在iOS模拟器中发出POST请求时,我收到此错误:

  Error Domain=com.alamofire.error Code=-6003 
    "Response status code was unacceptable: 500" 
UserInfo={StatusCode=500, NSLocalizedFailureReason=Response status code was unacceptable: 500}

我读到500错误代码很可能是服务器端问题,但只是为了确定 - 这是我的Swift代码:

let url = "http://localhost:3000/newproduct"


    Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in

        let image: UIImage = self.productImage.image!

            if let imageData = UIImagePNGRepresentation(image) {
                multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "fileName.png", mimeType: "image/png")
                multipartFormData.appendBodyPart(data: self.titleLabel.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"title")
                multipartFormData.appendBodyPart(data: self.descriptionLabel.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"description")
                multipartFormData.appendBodyPart(data: self.priceLabel.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"price")
        }

        }, encodingCompletion: { encodingResult in

            switch encodingResult {
            case .Success(let upload, _, _):
                upload.validate()
                upload.responseJSON { response in

                    switch response.result {
                    case .Success:
                        print("success")




                    case .Failure(let error):
                        print(error)
                    }

                }
            case .Failure(let encodingError):
                print(encodingError)
            }

    })

我也提到了这篇文章on Stackoverflow

如果您需要更多详情,请告诉我们。我的API是一个大文件,因此我不想上传所有内容。

0 个答案:

没有答案