I have controller in Laravel:
public function addUserTesterPost(Request $request)
{
$requestContent = json_decode($request->getContent(), true);
$emil = $requestContent->email; //error: $requestContent is null
}
this is json that I received in $request->getContent():
{
'email': 'dean',
'psw': 'dean123',
}
How to parse above json to object to fetch email?
I send request from Postman, in header I have set content-type: application/json.
This is an array json_decode($request->getContent(), true);
The -> cannot be used for array, instead use [ ] $requestContent['email'];
Related
Controller code:
[Route("api/[controller]")]
[ApiController]
public class AjaxController : ControllerBase
{
ApplicationDbContext dbContext = null;
public AjaxController(ApplicationDbContext ctx)
{
dbContext = ctx;
}
[HttpGet]
[Route("GetString")]
public string GetString()
{
return "Hello World";
}
[HttpGet]
[Route("GetCategories")]
public Category[] GetCategories()
{
return dbContext.Categories.ToArray();
}
}
Angular code:
http.get<string>(baseUrl + 'api/ajax/GetString').subscribe(result => {
console.log(result);
}, error => console.error(error));
While Angular can parse without error the GetCategories endpoint, it cannot parse the much simpler GetString. Why? The error in the console is:
error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
text: "Hello World"
I tried wit Postman and the response is just fine, see screenshot:
The issue is your response from GetString is returning just a string of value Hello World as shown by the screenshot from Postman. The GetCategories endpoint must be returning valid JSON if you are getting a valid response.
By default Angular assumes the response type of a HttpRequest to be of type json.
To fix this, specify as the second parameter to http.get() the responseType expected from the server which in your case for the GetString endpoint will be 'text'. So your http.get() call should look like the following:
http.get<string>(baseUrl + 'api/ajax/GetString', { responseType: 'text' }).subscribe(result => {
console.log(result);
}, error => console.error(error));
If your intention was to return valid JSON from GetString then you need to format the response from your server as appropriate.
See the Angular documentation on HttpRequest - responseType. I've included a copy below.
responseType: 'arraybuffer' | 'blob' | 'json' | 'text'
The expected response type of the server.
This is used to parse the response appropriately before returning it to the requestee.
I have an array that I'm converting to JSON using JSON.stringify
const arrayOfUpdatesAsJSON = JSON.stringify(this.ArrayOfTextUpdates);
This outputs some valid JSON.
[{"key":"AgentName","value":"Joe Blogs"},{"key":"AgentEmail","value":"Joe#test.com"}]
As I'm going to be sending JSON to the server I set the content type to application/json
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
When a button is pressed I make the request with the url, body and header.
try {
this.httpservice
.post(
url,
arrayOfUpdatesAsJSON,
httpOptions
)
.subscribe(result => {
console.log("Post success: ", result);
});
} catch (error) {
console.log(error);
}
This works fine and hits the method I'm expecting inside the api.
[HttpPost("{id:length(24)}", Name = "UpdateLoan")]
public IActionResult Update(string id, string jsonString)
{
Console.WriteLine(jsonString);
... and some other stuff
}
The ID is populated inside the url builder which populates ok. I would then expect the contents of my variable jsonString inside the api to be populated with the json of my request however it is always null. What am I missing?
Firstly you need to mark jsonString with [FromBody] to tell model binder bind the parameter from posted json. And because you are expecting plain string value you need to pass valid json string (not object) so you need to call additional JSON.stringify in javascript
const jsonArray = JSON.stringify(this.ArrayOfTextUpdates);
const arrayOfUpdatesAsJSON = JSON.stringify(jsonArray);
this.httpservice
.post(
url,
arrayOfUpdatesAsJSON,
httpOptions
)
Controller
[HttpPost("{id:length(24)}", Name = "UpdateLoan")]
public IActionResult Update(string id, [FromBody] string jsonString)
I am returning the object directly in the GET request as following.
Ok(object);
and the response json is given as,
json data-->
{
"id":"1",
"name":"testname"
}
I want to add some more details to this json
-->
{
success:"true",
messageDetails:"The response is returned by the service",
data:{}
}
how to accomplish this?
can i club all the things in Ok(object) ??
You can make use of an anonymous type, for example:
object data = new { id = 1, name = "testname" };
return Ok(new
{
success = "true",
messageDetails = "The response is returned by the service",
data
});
What's the best way to obtain this response to invalid form?
Response example of an invalid form
Actually I have this action
public function postUserAction(Request $request)
{
...
$form->handleRequest($request);
if ($form->isValid()) {
...
return $this->handleView($view);
}
$errors = $form->getErrors(true);
$view = $this->view($errors);
return $this->handleView($view);
}
But the response is the next json object:
{ form: Object, errors: Array }
I work with JMSSerializerBundle. I saw in FormErrorNormalizer class the method normalize in FOSRestBundle.
Thanks,
Request's handleRequest is for html forms. You have to use submit instead for FOSREST.
$form->submit($Request->getContent());
I'm trying to make request to facebook REST APIs and in return getting a JSON Response. I'm able to collect the response in REST client, hence I know the requestUrl I'm using while creating HttpRequest in following code is correct. But when I try to mimick the GET using akka-http javadsl, I'm unable to understand how to extract the json from the ResponseEntity.
final HttpRequest request = HttpRequest.GET(requestUrl);
final Materializer materializer = ActorMaterializer.create(this.context.getActorSystem());
final CompletionStage<HttpResponse> responseFuture =
Http.get(this.context.getActorSystem()).singleRequest(request, materializer);
final HttpResponse response = responseFuture.toCompletableFuture().get();
I'm expecting a response something as follows -
{
"data": [
{
"cpc": 9.7938056680162,
"clicks": "247",
"impressions": "15949",
"spend": 2419.07,
"date_start": "2016-06-15",
"date_stop": "2016-08-13"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
}
You should get response entity from response by calling ResponseEntity entity = response.entity() and after that call entity.toStrict(timeoutMillis, materialiser).data.decodeString("UTF-8") to get body string
You can lookup signatures of those methods in official API documentation