【发布时间】:2018-07-11 04:38:08
【问题描述】:
我必须使用作为 JSON 字符串的 application/x-www-form-urlencoded 值的标头进行 API 调用。在邮递员中给出参数值和标题时,它工作正常并返回状态码200 ok。我在这里使用后端 node js 。 Post 方法在前端不起作用。不知道是什么问题。
错误:
Sometimes i am getting request time out,
NSUrlfailingstring, finished with status code 1001
这是我的后端代码:
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);
};
这是我在 ios Swift 中的前端代码:
尝试 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
}
}
}
尝试 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()
任何帮助都非常感谢。
【问题讨论】:
-
在后端检查,检查您是否正在获取数据?
-
@PratikPrajapati 我在邮递员中获取数据
-
我的意思是,当您从设备/模拟器请求时,您是否获取数据
-
@PratikPrajapati 出现错误并出现错误 - 代码:-1001 可选(错误域=NSURLErrorDomain 代码=-1001“请求超时。” UserInfo={NSUnderlyingError=0x1c0e56920 {错误域=kCFErrorDomainCFNetwork 代码= -1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=highavenue.co:9000/likesnotification, NSErrorFailingURLKey=highavenue.co:9000/likesnotification, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=请求超时。} ) 基于 Dipen Chudasama 的回答
-
@PratikPrajapati 是的,我正在获取数据
标签: ios swift xcode alamofire nsurlsessiondatatask