无法从Alamofire向ExpressJs发送POST请求

时间:2019-08-28 09:35:39

标签: node.js express mongoose alamofire formidable

我将NodeJs / ExpressJs作为后端服务器(Ubuntu 18.04.3 LTS),当我从前端(JavaScript)或POSTMAN发出AJAX GET或POST请求时,它工作得很好(符合预期)。 当我使用Alamofire(swift)发出GET请求时,它也按预期工作,但是当我从Alamofire发出POST请求时,空数据将发送(或接收)到NodeJs / ExpressJs服务器。

在我的NodeJs服务器中,我正在使用强大的语法来解析正文(FormData),而在我的前端(JavaScript)中,我正在使用FormData api和标头content-type: false发送数据。 当我从Alamofire向我的后端服务器发送POST请求时,在其中设置了标头

  1. 内容类型为假
  2. 内容类型为multipart / formdata
  3. 没有内容类型

但仍在发送空数据(或在服务器上接收到空数据)

alamofire代码

 func uploadPostWithImageAndText() {

        let parameters = [

            "shared" : "Public",

            "post": self.textView.text

            ] as [String : Any]



        let recovedUserJsonData = UserDefaults.standard.object(forKey: "userData")

        let recovedUserJson = NSKeyedUnarchiver.unarchiveObject(with: recovedUserJsonData as! Data) as! NSDictionary

        //        print(recovedUserJson)



        var token = recovedUserJson.value(forKey: "token") as! String

        token = String(format: "%@", token)

        //        print(token)

        let headers = [

            "Authorization" : token

        ]

        let imgData = imgView.image?.jpegData(compressionQuality: 0.2)

        Alamofire.upload(multipartFormData: { multipartFormData in

            //Parameter for Upload files

            multipartFormData.append(imgData!, withName: "fileUpload",fileName: "fileUpload" , mimeType: "image/png")



            for (key, value) in parameters

            {

                  multipartFormData.append(key.data(using: .utf8)!, withName: value as! String)

            }



        }, usingThreshold:UInt64.init(),

           to: "https://apis.example.com/apis/feed/create-post", //URL Here

            method: .post,

            headers: headers, //pass header dictionary here

            encodingCompletion: { (result) in



                switch result {

                case .success(let upload, _, _):

                    print("the status code is :")



                    upload.uploadProgress(closure: { (progress) in

                        print("something")

                    })



                    upload.responseJSON { response in

                        print("the resopnse code is : \(response.response?.statusCode)")

                        print("the response is : \(response)")

                    }

                    break

                case .failure(let encodingError):

                    print("the error is  : \(encodingError.localizedDescription)")

                    break

                }

        })

在ExpressJ中,我具有用于FormData的正文解析器

app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(bodyParser.json({ limit: '50mb' }));

我正在使用formidable模块来解析正文。

我在Alamofire中遇到错误

<4> load failed with error Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x60000193f150 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <16AA23FC-8DFC-4598-B032-96636892F2B7>.<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(

    "LocalDataTask <16AA23FC-8DFC-4598-B032-96636892F2B7>.<4>"

), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=https://apis.example.com/apis/feed/create-post, NSErrorFailingURLKey=https://apis.example.com/apis/feed/create-post, _kCFStreamErrorDomainKey=4} [-1001]

并且我在后端将控制台记录了传入请求

console.log('fields', fields);

路线

router.post('/create-post' ,postCont.createPost);

其日志为空

fields {}

我不明白为什么后端(api端点)会收到空数据,谢谢。

1 个答案:

答案 0 :(得分:0)

我用nodemon替换了pm2,然后开始工作,我认为问题出在pm2。