简体   繁体   English

iOS和Node:将内容类型设置为application / json的正确方法

[英]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. 我正在开发连接到客户端iOS应用程序的后端Node应用程序。 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. 通过使用Afnetworking和AFHTTPSessionManager的子类化,当responseSeralizer设置为AFHTTPResponseSerializer并接受“ text / html”作为内容类型时,我能够以十六进制数形式获取数据。 However I get an error when setting the responseSeralizer to AFJSONResponseSerializer because node won't send the data as json data. 但是,将responseSeralizer设置为AFJSONResponseSerializer时出现错误,因为节点不会将数据作为json数据发送。 I can't seem to get my node backend to send "application/json" as the content-type. 我似乎无法让我的节点后端发送“ application / json”作为内容类型。 It continuously sets the content-type as "text/html" instead. 它将内容类型连续设置为“ text / html”。 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! 我已经尝试了多种方法,但到目前为止没有任何效果,但是我相信Stack Overflow社区! Let's go. 我们走吧。

iOS Client side: iOS客户端:

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: 节点JS / Express端:

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. 它将返回Json作为响应。

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. 这将是在Request中添加标头字段的最简单方法。

According to the Express 4.x API reference, the correct way to set Content-Type is by using res.type 根据Express 4.x API参考,设置Content-Type的正确方法是使用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 OR res.set设置任何标题

 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. 如果使用3.x,则只能使用res.set

Try this line res.set({ 'Content-Type': 'application/json; charset=utf-8' }); 试试这一行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 . 另一个选择是不设置'Content-Type'标题,而仅调用res.json that way express will set the header for you. 这样Express将为您设置标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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