I know how to send a post request with angular to an API, but was wondering how to retrieve post request sent from an application.
Let say I have this C# post request:
public string sendPost(string data)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://localhost:5000/app/edit");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{\"data\":\"" + data + "\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
In my angular app I have this controller:
(function () {
'use strict';
angular.module('anbud')
.controller('editController', ['$scope', 'localStorage', 'md5', '$routeParams', 'httpError',
function ($scope, localStorage, md5, $routeParams, httpError) {
function processHeaderData() {
console.log($routeParams.json);
}
processHeaderData();
}]);
}());
I can send data via a the url and use routeParams, but I would like to use POST instead. How do I access the POST data?
I think you are mixing up front end and web server technologies.
Angular is a front end technology, what you mean sending a post to angular, actually means sending a request to the web server that hosts the angular website.
Once you make this clear, you just need to send an API call to the web server like how you do with angular, and the server will return the json data you need.
If you want to get the HTML representation of particular route, I'm afraid there is no good way to achieve this. This is not particular with angular either, any site that loads data with ajax call would have this problem.
Angular $http.post can also retrieve data. For security purposes, this is quite beneficial. Logic for that remains the same.
You could send data from your c# controller through this:
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Sample.API.Controllers
{
public class ContentDataController
{
[Route("api/ContentData")]
[HttpPost]
public HttpResponseMessage SamplePost(SampleRequest request)
{
HttpResponseMessage response;
try
{
var cda = dataContentAdapter();
//Business logic here
var result = cda.GetContent(request);
//pass the above result to angular
response = Request.CreateResponse(HttpStatusCode.OK, result);
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
}
catch (Exception ex)
{
ApplicationLogger.LogCompleteException(ex, "ContentDataController", "Post");
HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } };
return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError);
}
return response;
}
}
}
With this, send a request from angular with whatever data that needs to be used in request. Favorable is to send json, parse the json in your business logic.
Create a HttpResponseMessage with the new payload for angular $http to recieve.
Related
As a new comer to ASP.Net looking for workaround on, redirecting to another URL at the end of the HttpResponseMessage POST api.
In reference to Redirect from asp.net web api post action I tried same procedure to redirect. Api returns response to caller but no redirect is happening. The Api call response goes to fail callback on javascript side.
Any suggestion on solving this is greatly appreciated.
Tried calling Post API from Javascript. Always throws error with CORS.
// C# API
[HttpPost]
[Route("SignInTest")]
public HttpResponseMessage Post(SignInModel signInModel)
{
HttpResponseMessage response = null;
EntityResponse<UserAuthenticationDTO> userAuthenticationDTOResponse =
_authenticationService.Validate(signInModel.Login, signInModel.Password);
if (userAuthenticationDTOResponse.IsSuccess)
{
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://sample.com"); // to url that I have to redirect
return response; // expected https://sample.com to load
}
response = Request.CreateResponse(HttpStatusCode.InternalServerError, ErrorCode.AccountVerificationEmailIsNotVerified);
return response;
}
// Javascript Caller
dataContext.singleSignOn.SignInTest(self.validatedObservable).done(function (data)
{
console.log("data", data);
}).fail(function (error)
{
console.log("done with error", error); // Always throws error with CORS for https://sample.com to load .
});
I am trying to save a file on the client side of my react application.
The data is obtained from my API Controller called DownloadDocument.
I am returning FileSreamResult from my DownloadDocument method.
FileStreamResult reads the data and writes it to the response in the react API.
The network tab gets a response, but when i log the response i get a response of null.
I am using file-saver to try and save the file. https://www.npmjs.com/package/file-saver.
Does anyone have any recommendations on what the issue is or if there is a better way of doing?
My action in the controller:
The issue that i am having is that my response for the react api is coming back null.
[HttpGet("{documentId}")]
[AcceptVerbs("OPTIONS", "GET")]
[AllowAnonymous]
public async Task<IActionResult> DownloadDocument(int documentId)
{
if (documentId != 0)
{
var document = await service.DownloadDocumentAsync(documentId);
var documentResponse = File(document, "application/octet-stream");
return documentResponse;
}
return BadRequest("Document id is not valid");
}
react application.
api.indexes.downloadDocument(clones)
.then(response=>{
console.log(response)
let FileSaver = require('file-saver');
let blob = new Blob([response], {type: "application/octet-stream"});
let filename ="testdownload"
FileSaver.saveAs(blob, filename)
Thanks for the help.
I needed to add this to the header.
responseType: 'blob'
this article explains it well
https://medium.com/#fakiolinho/handle-blobs-requests-with-axios-the-right-way-bb905bdb1c04
In my Maven app I have mapped put http request onto this function(using spring framework), and I want to check something inside it and send response as text. Then I want to send that request from angularjs and store that response into some variable from angularjs controller. This is what I have tried.
#RequestMapping(path="/play", method={RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String someFunction(){
//...
return "some text";
}
$scope.getResponse = function(param1, param2...){
$http.post("url..").then(
function(response){
$scope.response = response.data.response;
console.info('success');
},
function(response){
console.info('failure');
})
}
Http is mapped correctly and works from browser, problem is how to store textual response into some angularjs variable from controller.
It seems $http finds it difficult to parse the invalid JSON data in the response.
We have produces = {MediaType.APPLICATION_JSON_UTF8_VALUE} in there for the API and sending out plain text. That's why it goes to the failure handler.
Change the media type to MediaType.TEXT_PLAIN_VALUE and see if it works...
I'm working with a Java backend with Spring MVC framework, I have a service that takes a List and remove some objects in a database. When I use Postman I send the next JSON object:
["ce8249aa-1ede-40b9-a158-d2c417c23df7",
"73a629b9-bae8-44aa-83c3-e8ee0fc96325",
"50c45e52-2c74-40ec-93e7-1b5379eae5db",
"c8a61e92-bc6d-47d0-a3e2-bda9ad85cecc"]
Then I used a service in Angularjs sending this object:
$scope.accounts = new Array("ce8249aa-1ede-40b9-a158-d2c417c23df7",
"73a629b9-bae8-44aa-83c3-e8ee0fc96325",
"50c45e52-2c74-40ec-93e7-1b5379eae5db",
"c8a61e92-bc6d-47d0-a3e2-bda9ad85cecc");
But I got this error:
The request sent by the client was syntactically incorrect.
This problem does not occurs with other JSON objects, for example:
From Postman:
{
"accountName":"XxxxxXXxxxx",
"paymentMethodMain":"Medio Pago",
"accountType":"xx",
"accountNumber":"123456AA"
}
And from Angular:
$scope.account = {
"accountName":"XxxxxXXxxxx",
"paymentMethodMain":"Medio Pago",
"accountType":"xx",
"accountNumber":"123456AA"
};
In this case all works correctly.
I think you can't post an array like this. Either you have to send the array as string/text in request body and parse in server side or do something like
$scope.accounts = new Array("ce8249aa-1ede-40b9-a158-d2c417c23df7",
"73a629b9-bae8-44aa-83c3-e8ee0fc96325",
"50c45e52-2c74-40ec-93e7-1b5379eae5db",
"c8a61e92-bc6d-47d0-a3e2-bda9ad85cecc");
// in your request send the array as value to a json key
{data: $scope.accounts }
in your server try
request.getParameterValues("data[]");
My controller in Grails first fetches the data from a remote service API, and the returned data is a String. Then I would like to have the data downloaded as a csv file in the browser. I came across a similar post on SO and stole the code for using the response as below:
String exportResults = dataService.getDataFromService()
response.setHeader "Content-disposition", "attachment; filename=data_export.csv"
response.contentType = 'text/csv'
response.outputStream << exportResults.getBytes() //getBytes() not portable
response.outputStream.flush()
But this does not trigger any download window in the browser. I was wondering why. I use AngularJS to make a POST request to the controller and resolve the promise as below (JavaScript code):
ExportService.exportData(some_params).then(function(data) {
$log.info('export promise resolved: ');
//window.open(data, '_blank', ''); //not working
}).catch(function(err) {
$scope.message = "failed to retrieve data from export service";
$log.error(err);
}).finally(function(complete) {
$scope.message = "Data export completed.";
});
You need to replace 'text/csv' with 'application/octet-stream' for response.contentType. The content type 'application/octet-stream' is used for a binary file.
Try adding this after response.outputStream.flush() and see if it works.
webRequest.renderView = false
You can even try looking here.