Requests with Alamofire 4 in Swift 3 always fails with 500 status code. I tryed in Postman and works!
Look at my code:
func newUser(user: User) {
var urlRequest = URLRequest(url: URL(string: url + "/register")!)
urlRequest.httpMethod = "POST"
let parameters: Parameters = [
"username": "\(user.name!)",
"email": "\(user.email!)",
"password": "(Kh=CE)4r)PC4}f?",
"profile": [
"status": 0,
"level": 0,
"facebook_id": "\(user.fbId!)",
"facebook_token": "000",
"push_device_token": "000",
"photo": "\(user.photoUrl!)"
]
]
let headers: HTTPHeaders = ["Content-Type": "application/json"]
Alamofire.request(url+"/register", method: .post, parameters: parameters, encoding: JSONEncoding(options: []), headers: headers).response { response in
debugPrint(response)
print(response)
}
}
Anyone can help me?
I have done the same thing you are trying to accomplish and the only difference I see is your header, try changing it to:
let headers = ["Authorization": )", password]
Wireshark can also help you to see the exact reason for the 500 error.
Related
I'm trying to use Google Identity platform api's with my firebase project ( I configured a payment method to use the identity platform sendOobCode and sendVerificationCode methods. But I keep receiving a 400 ERROR.
I tried using the built-in api calls in the console and got back more detailed errors.
"errors": [ { "message": "CONFIGURATION_NOT_FOUND", "domain": "global", "reason": "invalid" } ] }
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
var url = 'https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=[]';
var data = {
// requestType: "VERIFY_EMAIL",
idToken: userCredential._tokenResponse.idToken
}
console.log(userCredential)
axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
})
.catch((error) => {
.....
})
So I was able to get more information on my error by going into the Network Section in the dev tools. I checked the 400 request error and found in the response that I have an invalid API key. I forgot to remove the [] :)
I'm trying to upload a file in swiftUI, using multipart form-data
The code is like this:
do {
let data = try Data(contentsOf: url)
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(data, withName: "uploadedFile",fileName: "uploadedFile",mimeType: "text/plain")
}, to: "https://server.com/upload",headers: ["Authorization" : "Bearer \(API.shared.accessToken!)",
"Content-Type": "multipart/form-data"])
.responseDecodable(of: String.self ) { response in
debugPrint(response)
}
}
catch {
print("Error \(error)")
}
Where url is a local URL, DocumentPickerViewController has provided.
For some reason the server gives an error saying something went wrong.
This is the response I picked up in Charles:
And this the response I picked up in Postman (which works):
I noticed that postman automatically generated the Content type parameter in the formdata (which was an image in this test, but it could be any file type). Alamofire didn't do that by default, so I added filename and the mimetype (text/plain) in the request, but that didn't work.
Any thoughts? It works on Postman. So is this a server issue or a frontend issue?
This code worked for me , for uploading an image file
I used "application/x-www-form-urlencoded" instead of "Content-Type": "multipart/form-data"
let url = "url here"
let headers: HTTPHeaders = [
"Authorization": "Bearer Token Here",
"Accept": "application/x-www-form-urlencoded"
]
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image" ,fileName: "image.png" , mimeType: "image/png")
}, to: url, method: .post ,headers: headers).validate(statusCode: 200..<300).response { }
In tests section, I try to set token as Postman variable. I get the following error:
SyntaxError: Invalid or unexpected token
Here's my script in test tab:
var data = pm.response.json();
pm.environment.set(“token”, data.token);
and here's my response for login:
{
"id": 1,
"username": "admin",
"name": "John",
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU2OTY3ODg4NSwiaWF0IjoxNTY5MDc0MDg1fQ.k6aMQYo9uzC9jEXFvP1EZEUNEG_7VgEKxKmNtrZ9rSYvViHCNGYMaEpYY7MH8rYgtIg1Lpi4bfZEd9q2iOEOSQ"
}
Content type of response is application/json;charset=UTF-8.
What am I missing?
Notice the difference between " and “
pm.environment.set(“token”, data.token);
should look like this
pm.environment.set("token", data.token);
I'm trying to make a request sending parameters by POST, Alamofire request says that its POST, but my server get the parameters by GET.
let formParams:[String : String] = ["facebook_id": COUtils.userProfile["id"]!, "full_name": name, "email": mail, "phone": phone , "state": state, "device_id": UIDevice.current.identifierForVendor!.uuidString, "device_type": "ios"]
let headers = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded",
"Authorization": COUtils.autorizationBearer
]
print(COUrls.apiUrl + COUrls.register, formParams)
Alamofire.request(COUrls.apiUrl + COUrls.register, method: HTTPMethod.post, parameters: formParams, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
print(response.response?.allHeaderFields ?? "")
Thanks in advance
Here I am trying to upload a video to user profile.
I have set up javascript sdk and my authentication works well .
I have the following code here..
FB.api(
`/${user_id}/videos`,
"POST",
{
"file_url": video,
"description": description,
"thumb": video_thumbnail,
"title": title,
},
function (response) {
console.log("fb response")
console.log(response)
if (response && !response.error) {
/* handle the result */
console.log("video upload response")
console.log(response)
}
});
Here I get the following error ..
code: 100
fbtrace_id: "FD5tVyrH9bS"
message: "(#100) Invalid format. It should be an image file data."
type: "OAuthException"
I am using file_url and passing url to my video. I guess it should upload the video..
Thank you for the response
I confirm that you must post image file data in source field when posting to Facebook.
You can test by use Postman.
This is example:
var fs = require("fs");
var request = require("request");
var options = { method: 'POST',
url: 'https://graph.facebook.com/v2.11/2011156779127713/thumbnails',
headers:
{ 'Postman-Token': '6c17c103-d8f6-47a5-713b-b3709dde762d',
'Cache-Control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{ access_token: 'test',
is_preferred: 'true',
source:
{ value: 'fs.createReadStream("./Downloads/923249_818835191462845_1528674847924045075_n.jpg")',
options:
{ filename: './Downloads/923249_818835191462845_1528674847924045075_n.jpg',
contentType: null } } } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The problem isn't the video or the URL, it's the thumb parameter.
The thumb parameter needs to be 'file data', not the URL.
As to what format the image needs to be in..please let me know if you find out! I'm asking the same here.
The facebook API is terrible...