Cannot get data with AngularJS + Azure WCF - json

I'm trying to get data from my website using AngularJS to my wcf in Azure but i'm getting error.
In my js:
$http({
url: dataService.serverPath + 'Services.svc/Login',
method: 'GET',
headers: { 'Accept': 'application/json, text/plain',
'Content-Transfer-Encoding': 'application/json;charset=utf-8',
'Accept-Charset': "charset=utf-8",
},
params: { key: key }
}).success(function (data, status, headers, config) {
//some code here
}
}).error(function (data, status, headers, config) {
$scope.hasError = true;
$scope.errorMsg = "The request failed: " + data;
});
fiddler response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 11 Aug 2015 22:17:09 GMT
Transfer-Encoding: chunked
49
{"ID":0,"NomeUsuario":"Admin","IsAdmin":true,"Error":null}
0
Note, i'm getting HTTP 200 and i'm getting error.
The return data is 49 { Json } 0, what is it?
I tried to remove the Transfer-Encoding: chunked from my WCF but no success.
I spend this hole day trying getting data from Azure and i didnt. Running on my dev machine, it's fine and does not show Transfer-Encoding : Chuncked nor the 49 and 0 enclosure my JSON.

first thing that came to my mind was the MIME type as it needs to be changed by FTPing to your Website in Azure and updating the WebConfig file. But this usually returns 404 as in your case it returns 200, still no harm to check.
My other suggestion would be about the WebInvoke inside your WCF (if you are using it) following piece should set your WCF for Json usage.
[WebInvoke(UriTemplate = "Your template here",
Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebmessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
Hope this helps

Related

Save File And Json Data Via Angular and Spring boot

i have had this bug for a long peroid now, was trying to figure it out myself but am not getting it, it's an angular/spring boot app that am trying to upload different files and also save a json data at the same time, i have gone through previous questions concerning it but it hasn't worked for me, but when i tried saving the data via postman it works perfectly but not the same with angular, please i will appreciate the assistance...
this is my component.ts file containing the function
addBeat(artWork: File,untaggedmp3:File, taggedmp3:File){
const formData:FormData = new FormData();
if(artWork){
formData.append('artWork', artWork)
}
if(untaggedmp3){
formData.append('untaggedmp3', untaggedmp3)
}
if(taggedmp3){
formData.append('taggedmp3', taggedmp3)
}
this.beat.name = this.addBeatForm.get('name').value;
this.beat.price = this.addBeatForm.get('price').value;
this.beat.tempo = this.addBeatForm.get('tempo').value;
this.beat.description = this.addBeatForm.get('description').value;
this.beat.beatKey = this.addBeatForm.get('beatKey').value;
this.beat.mood = this.addBeatForm.get('mood').value;
this.beat.genre = this.addBeatForm.get('genre').value;
formData.append('beatDto', JSON.stringify(this.beat));
this.beatService.uploadBeat(formData)
.subscribe(
(data)=>{
console.log(data);
}
);
}
And my service.ts
public uploadBeat(formData: FormData): Observable<BeatDto>{
return this.httpClient.post<BeatDto>(`${this.apiServerUrl.admin}/api/beat/single/upload`, formData,
{headers: {
'Accept':'multipart/form-data',
'mimeType': 'multipart/form-data'}}
));
}
and my springboot rest controller is this
#RestController
#RequestMapping("/api/beat")
#AllArgsConstructor
#Slf4j
public class BeatController {
private final BeatService beatService;
private final FileStorageService fileStorageService;
#PostMapping(path = "/single/upload", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<BeatDto> uploadBeat(#RequestParam("beatDto") String beatDto,
#RequestParam("artWork") MultipartFile artWork,
#RequestParam("taggedmp3") MultipartFile taggedmp3,
#RequestParam("untaggedmp3") MultipartFile untaggedmp3){
BeatDto beatJson = beatService.getJson(beatDto,artWork,taggedmp3,untaggedmp3);
return ResponseEntity.status(HttpStatus.CREATED).body(beatService.uploadBeat(beatJson,artWork,taggedmp3,untaggedmp3));
}
}
so when i test in on the browser i get a error code 400 on the browser console...
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 400,
"statusText": "OK",
"url": "http://localhost:8081/api/beat/single/upload",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://localhost:8081/api/beat/single/upload: 400 OK",
"error": null
}
And also from my network tab
Request URL: http://localhost:8081/api/beat/single/upload
Request Method: POST
Status Code: 400
Remote Address: [::1]:8081
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Expose-Headers: Origin, Content-Type, Accept, Authorization
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Length: 0
Date: Thu, 06 Jan 2022 02:02:41 GMT
Expires: 0
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Accept: multipart/form-data
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 638
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFUAjEynxdkQfpcfA
Host: localhost:8081
mimeType: multipart/form-data
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
main.app
#SpringBootApplication
#EnableAsync
#Import(SwaggerConfiguration.class)
public class BasicApplication {
public static void main(String[] args) {
SpringApplication.run(BasicApplication.class, args);
}
#Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
corsConfiguration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
security config
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**", "/webjars/**", "/assests/**").permitAll()
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html")
.permitAll()
.antMatchers("/api/auth/**").permitAll()
.antMatchers(HttpMethod.GET,"/api/beat/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/beat/**").permitAll()
.anyRequest()
.authenticated();
httpSecurity.addFilterBefore(jwtAuthFilter,
UsernamePasswordAuthenticationFilter.class);
}
Thanks In Advance

Node.js Request GET returning raw data instead of JSON [duplicate]

This question already has answers here:
Encoding issue with requesting JSON from StackOverflow API
(2 answers)
Closed 5 years ago.
I have a particularly interesting issue, So I am trying to use Stackoverflow Search/Advanced API to query stackoverflow to get questions. I have tried it using PostMan and its returning JSON but in my Node.js application it is returning me raw data.
exports.GetQuestions = function(query,requestify)
{
var request = require("request");
var options = { method: 'GET',
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
}`
I generated the code for the request using postman itself, I tried it on different API and the same code is working fine.
I need help in figuring out how to get JSON as response.
Here is the response:
cache-control: private
content-type: application/json; charset=utf-8
content-encoding: gzip
access-control-allow-origin: *
access-control-allow-methods: GET, POST
access-control-allow-credentials: false
x-content-type-options: nosniff
date: Sun, 21 Jan 2018 16:12:19 GMT
connection: close
content-length: 4780
Here is a sample of data returned:
���������U����"�z�f%��-??ӵm��N�|�f&��fે�n�.""��DX�Ƀ�P��J�(�p�U�Q�N47 �1�M�.�|]�t5agA��0�rc �g�3��}
+�Y�q/�pL��M�RƜGwt�B��ڍ�#���9(>s��ʀ6�#�w���e/��Mu�ʮ��9,�ML|
�s9�a���ߑW�r�[����ߗa�������a�~6��>ͦ����u�3���a�|P-�ᣖ�S'
�
򄾤�#v�D�PXM�i��ȹ��O�{2N�s��?
����ڝ���O_������/ ���ř��M3��w�ܾ����g"�� ���$�(%"�r#S�Px3��;?4^}�܏�n�S�f7U[���g7�
a�cȩbҷ�Oq����X,8w�5Szp�P�y���rg�<�������m�;�u���|��aXJ��!��~X�bK�#�b5���,)W+����)������+n[cl()�����lC>
okoSHcY��c\�TW0ƊLM
��ݒ���oN9دhV���t��rj��
*�cPޝ�~l���E�́Ѳ�o3Dp�Eus侫��L��R�n��i�`+����DF���h $~377s=��W��xP��#�CAN�1�T�Ub0c$�e����S���&���B�}�~��Q�������m��m�������a�|���sL�Y;z8��T}�j~�]޽}���El�����]|��B�����*nt�^�,�����
k'
7�J�IO�i�d�m�4"�N���DZ��1䞦'�[�&�j���~�6�).G��v=��gn��x4�6nh�����V��o�)���^ಧ�2����['6����z� �#�/���J���j+vD�xƍ)N����qC[C���U��Z|�����vh���_��>�gd�9��v���.��i�U�zJ��,�*J��RBt�s��iӮo��f�^A3��$�"7�N��!�l�b,"��96�#�������C���.��a�52'a�v�U��9��v]�l�~kΎ��ԌG�藊<9�eN;]t��n�k?;cu� L�u}�t���q;৯��=�����Y��ZK������AL.�L
The response you received is gzip compressed as shown by content-encoding: gzip.
Set gzip:true in your options.
var options = { method: 'GET',
gzip: true,
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };

HttpResponseMessage not showing JSON content from MVC relay to Web Api

I am using an MVC relay controller to call a Web Api controller to get around the PUT limitation in forms/browsers. The relay works fine. The problem is that the response when displayed just shows the response code and headers and not the JSON content that is also returned.
Here is the code that does the relay:
[HttpPost]
public async Task<HttpResponseMessage> UpdateTicket(int reference, TicketUpdateDTO ticket)
{
HttpClient client = new HttpClient();
var baseUri = string.Format("{0}://{1}{2}", Request.Url.Scheme,
Request.Url.Host, Request.Url.Port == 80 ? string.Empty : ":" + Request.Url.Port);
client.BaseAddress = new Uri(baseUri);
HttpResponseMessage responseMessage = await client.PutAsJsonAsync("api/Tickets/" + reference, ticket);
var content = await responseMessage.Content.ReadAsStringAsync();
return responseMessage;
}
And here is what is actually returned and displayed in a browser:
StatusCode: 201, ReasonPhrase: 'Created', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache X-SourceFiles: =?UTF-8?B?QzpcRGV2ZWxvcFxFeHRyZW1lSVRTXEV4dHJlbWVJVFNcYXBpXFRpY2tldHNcMTAwMDAwMg==?= Cache-Control: no-cache Date: Fri, 26 Feb 2016 16:32:57 GMT Location: http://localhost:59413/api/tickets/1000002 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 419 Content-Type: application/json; charset=utf-8 Expires: -1 }
When I check the content, it is returning the object correctly in JSON format, but I am not sure why it isn't showing up in the browser with all the other parts of the HTTP response not shown.

windows phone 8.1 - api - sign up and login

I have got problem with using HttpClient in Windows Phone 8.1 application. I'm new in this WP 8.1 class.
I write this code:
var uri = new Uri("http://testapiurl.com");
var message = new
{
Name = "Test",
Surname = "Test",
Mail = "test#test.pl",
Password = "test1234"
};
var json_object = JsonConvert.SerializeObject(message);
HttpStringContent stringContent = new HttpStringContent(json_object.ToString(), UnicodeEncoding.Utf8, "application/json");
var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(
uri,
stringContent);
Debug.WriteLine(response);
After compilation and running I got message
StatusCode: 200, ReasonPhrase: 'OK', Version: 2, Content: Windows.Web.Http.HttpStreamContent, Headers:
{
Connection: Keep-Alive
Server: Apache/2.4
Transfer-Encoding: chunked
Keep-Alive: timeout=10, max=100000
Date: Mon, 17 Aug 2015 04:59:02 GMT
X-Powered-By: PHP/5.4.39
}{
Content-Type: application/json; charset=UTF-8
}
In API help and examples I have information that in return it should be Status Code: 200 and name of created user. But I don't get it. Second thing is that when I push the second time the same code to create account I get back the same response. In help for API it should be error 409 conflict the same account already exist.
I don't know that this code is good, or am I missing big amount of code.
You need to use
var responseString = await response.Content.ReadAsStringAsync();
to get your response string. There will be everything from the actual response.
Your current code only writes the response headers and the content type.

Web api return null value

I have an Web Api controller for access data from server:
public class ServicesController : ApiController
{
[AcceptVerbs("POST")]
public IList<TreeMenuItem> LoadMetadata()
{
List<TreeMenuItem> itemsMenu = new List<TreeMenuItem>();
TreeMenuItem dataSource = new TreeMenuItem("1", "DataSources", null);
itemsMenu.Add(dataSource);
return itemsMenu;
}
}
which is call by an angularJS controler:
angular.module('App').
controller('TreeMenuController', ["$scope", "$http", treeMenuController]);
function treeMenuController($scope, $http) {
var baseUrl = "api/Services/LoadMetadata";
$http.post(baseUrl)
.then(function (result) {
$scope.roleList = result.data;
});
};
In browser network I have:
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate
Content-Length:2
Content-Type:application/json;charset=UTF-8
Request Payload
{}
Response Headers:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 4
in Response tab: [{}].
What is wrong?
I make it work:
The big help was the response message when I put in browser the address for accessing api services (api/Services/LoadMetadata):
The error answer was in an xml file where I found that was problem with serialization of the object TreeMenuItem. The advice was to decorate with DataContract the class and DataMember the class properties - like in WCF. After I did that (was need to add reference in project to System.Runtime.Serialization), everything was perfect.