简体   繁体   中英

iOS and Node: Correct way to set content-type to application/json

I'm working on a backend Node app that connects to a client iOS app. The only problem I'm having is with the response data. Using Afnetworking and subclassing AFHTTPSessionManager I'm able to get back data in the form of hexadecimal numbers when the responseSeralizer is set to AFHTTPResponseSerializer and accepts "text/html" as a content type. However I get an error when setting the responseSeralizer to AFJSONResponseSerializer because node won't send the data as json data. I can't seem to get my node backend to send "application/json" as the content-type. It continuously sets the content-type as "text/html" instead. My question is how to accomplish this for each get or post route I have where I'm send back a response? I've tried multiple things and nothing has worked so far but I believe in the Stack Overflow community! Let's go.

iOS Client side:

self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];


[self POST:MOBIAPIHost parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {

    completionBlock(responseObject);

    NSLog(@"response: %@", responseObject); 

} failure:^(NSURLSessionDataTask *task, NSError *error) {

    NSLog(@"error %@", error);

    completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);

}];

Node JS/ Express Side:

app.post('/api/signup', function(req, res){


res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
res.type({ 'Content-Type': 'application/json; charset=utf-8' });
var data = {
 json: "test to see if data variable goes through as json data"
} 
res.json({data:data});
});

Results:

{status code: 200, headers {
"Access-Control-Allow-Headers" = "X-Requested-With, content-type, Authorization";
"Access-Control-Allow-Methods" = "GET, POST";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 1158;
"Content-Type" = "text/html; charset=utf-8";
  }
}
response: <3c68746d 6c206c61 6e673d22 656e2220 6e672d61 70703d22 6d794170 70223e0a 
3c686561 643e0a20 2020203c 62617365 20687265 663d272f 273e0a20 2020203c 
7469746c 653e4d6f 62694d61 6c6c3c2f 7469746c 653e0a20 2020203c 6d657461 
206e616d 653d2276 69657770 6f727422 20636f6e 74656e74 3d227769 6474683d 
64657669 63652d77 69647468 2c20696e 69746961 6c2d7363 616c653d 312e302c 
206d6178 696d756d 2d736361 6c653d31 2e302c20 75736572>

In your node side you can try for this:

res.writeHead(200, {
    'Content-Type': 'application/json'
     });
 res.end(JSON.stringify(data, null, "\n"));
 return;

It will return Json as response.

You can set it like this,

 NSString *contentType = [NSString stringWithFormat:@"application/json"];
[fav_URL_Request addValue:contentType forHTTPHeaderField: @"Content-Type"];

This would be the simplest way to add header field in Request.

According to the Express 4.x API reference, the correct way to set Content-Type is by using res.type

res.type('.html');              // => 'text/html'
res.type('html');               // => 'text/html'
res.type('json');               // => 'application/json'
res.type('application/json');   // => 'application/json'
res.type('png');                // => image/png:

OR res.set to set any headers

 res.set('Content-Type', 'text/plain');

 res.set({
    'Content-Type': 'text/plain',
    'Content-Length': '123',
    'ETag': '12345'
 });

If using 3.x only the res.set is available.

Try this line res.set({ 'Content-Type': 'application/json; charset=utf-8' }); see if it solves your problem.

Another option is to not set the 'Content-Type' Header and call only res.json . that way express will set the header for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM