0

I have to make an API call with headers as application/x-www-form-urlencoded value as a JSON string. When give parameter value and header in postman, it works fine and returns status code 200 ok. Here i am using backend node js . Post method does not work in front end. Dont know what is the issue.

Errors:

Sometimes i am getting request time out, 
NSUrlfailingstring, finished with status code 1001

Here is the code of my backend :

  var status = {
SUCCESS : 'success',
FAILURE : 'failure'
}

var httpStatus = {
OK : HttpStatus.OK,
ISE : HttpStatus.INTERNAL_SERVER_ERROR,
BR : HttpStatus.BAD_REQUEST
}
exports.likes= function(req, res){

var Username =req.body.username;
var likecount=req.body.count;
var likedby = req.body.likedby;
var postId = req.body.postId;
var tokenId = req.body.tokenId;
var message = {
                     to: tokenId, 
                     collapse_key: '',
                     data: {
                        name:Username,
                        Message:"Content about message",
                        Redirect:"TopostId : "+postId,
                        time: ""
                      },
                     notification: {
                                    title: "Hey Buddy , Someone have liked your post",
                                    body: likedby +"Likedyourpost",
                                    icon: "notification"
                                    }
                };


fcm.send(message)
    .then(function (response) {
        console.log("Successfully sent with response: ", response);
        res.status(httpStatus.OK).json({
        status: status.SUCCESS,
        code: httpStatus.OK,            
        error:''
    });
            return;
            })
        .catch(function (err) {
             console.log(err);

            });

};


module.exports = function(app) {
app.post('/likesnotification', notification.likes);
app.post('/commentsnotification', notification.comments);
app.post('/othernotification', notification.othernot);
app.post('/followrequset', notification.followreq);
app.post('/followresponse', notification.followres);
app.post('/publicaccountfollow', notification.publicacfollow);

};

Here is my front code in ios Swift:

Try 1:

   func postNotification(postItem: String, post: Post) {

print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")




let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]

   let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

    switch(response.result) {
    case .success(_):
        if let data = response.result.value{
            print(data)
        }
        break

    case .failure(_):
        print(response.result.error as Any)
        break

    }
   }

}

Try 2:

 var parameters       = [String:Any]()

parameters["count"]  = post.likeCount!
parameters["likedby"]  = currentName
parameters["postId"] = postItem
parameters["token"] = post.token!

  let Url = String(format: "http://highavenue.co:9000/likesnotification")
guard let serviceUrl = URL(string: Url) else { return }
//        let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
let parameterDictionary = parameters
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
    return
}
request.httpBody = httpBody

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
    if let response = response {
        print(response)
    }
    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: 
    [])
            print(json)
        }catch {
            print(error)
        }
    }
    }.resume()

Any help much appreciated pls.

Pratik Prajapati
  • 1,137
  • 1
  • 13
  • 26
PvDev
  • 791
  • 21
  • 67
  • check at backend side, check you are getting data or not? – Pratik Prajapati Jul 11 '18 at 04:52
  • @PratikPrajapati i am getting data in postman – PvDev Jul 11 '18 at 05:23
  • what i mean is, Do you get data when you request from device/simulator – Pratik Prajapati Jul 11 '18 at 05:27
  • @PratikPrajapati getting error finished with error - code: -1001 Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x1c0e56920 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://highavenue.co:9000/likesnotification/, NSErrorFailingURLKey=http://highavenue.co:9000/likesnotification/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}) based on Dipen Chudasama answer – PvDev Jul 11 '18 at 05:27
  • @PratikPrajapati yes i am getting data – PvDev Jul 11 '18 at 05:28
  • might possible when you request from iOS device, server not detect some param values. compare postman and your device request data at backend side. hope you find something – Pratik Prajapati Jul 11 '18 at 05:37
  • @PratikPrajapati whether my front end code is correct?? – PvDev Jul 11 '18 at 05:39
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174765/discussion-between-pratik-prajapati-and-pvdev). – Pratik Prajapati Jul 11 '18 at 05:41

1 Answers1

0

I seen your code you are suppose to call the header parameter which was you create for it. You are not pass header in alamofire request method.

Like below :

let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]

   let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in

    switch(response.result) {
    case .success(_):
        if let data = response.result.value{
            print(data)
        }
        break

    case .failure(_):
        print(response.result.error as Any)
        break

    }
   }

}
Dipen Chudasama
  • 3,063
  • 21
  • 42
  • Getting error like this finished with error - code: -1001 Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x1c0e56920 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://highavenue.co:9000/likesnotification/, NSErrorFailingURLKey=http://highavenue.co:9000/likesnotification/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}) – PvDev Jul 11 '18 at 05:26
  • did you pass that header variable in alamo fire method as I mention above ? – Dipen Chudasama Jul 11 '18 at 05:46
  • Hey can you help me out of this – PvDev Jul 11 '18 at 06:08
  • Hey can you check out screenshots of postman....https://drive.google.com/file/d/1dmXvE2PoSnh9Dj0XVfGtMRu-IDKXETps/view?usp=sharing – PvDev Jul 11 '18 at 06:51
  • Pass header like this : let headers = [ "Content-Type" : "application/x-www-form-urlencoded" ] – Dipen Chudasama Jul 11 '18 at 11:37