node.js - 无法从 Alamofire 向 ExpressJs 发送 POST 请求

标签 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 服务器中,我使用 formidable 来解析正文 (FormData),在我的前端 (JavaScript) 中,我使用 FormData api 和 header 发送数据,content-type: false。 当我从 Alamofire 向后端服务器发送 POST 请求时,我在 header 中设置了

  1. 内容类型为 false
  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

                }

        })

在 ExpressJs 中,我有 FormData 的正文解析器

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

我正在使用强大的模块来解析正文。

我在阿拉莫菲尔遇到错误

<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端点)收到空数据,谢谢。

最佳答案

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

关于node.js - 无法从 Alamofire 向 ExpressJs 发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689297/

相关文章:

node.js - 我应该在每个模块中都要求吗?

node.js - 路径\"[object Object]\"处的值\"players\"转换为 ObjectId 失败

react-native - 如何将 react-native 图像从 expo-image-picker 上传到使用 multer 的 Express.js 后端

javascript - 如何使用rest api的动态查询

javascript - ExpressJS : call a variable from . js文件到index.html

node.js - 在使用 Bluebird promise mongodb 后,使用 mongodb 的查找游标的 next/each 函数作为 promise 的方法

javascript - 如何将 javascript if 条件移动到外部文件?

node.js - 新增 mongoose bool 属性,大家都为 true,默认为 false

javascript - 为什么分配属性后 save 不是一个函数?

node.js - 异常的 Mongodb 查询