I get an unknown character in json response with codeigniter - json

that character that the red arrow points to
I am doing the responses with codeigniter functions
$this->setResponseFormat('json')->respond(["status" => "error", "message" => "hello"], 200);
and when I consult it in postman that character appears.
I thank you can help me.
I am doing the responses with codeigniter functions
$this->setResponseFormat('json')->respond(["status" => "error", "message" => "hello"], 200);
and when I consult it in postman that character appears.
I thank you can help me.

Related

Fetch SyntaxError: Unexpected token < in JSON at position 0

hey guys im having some wierd issue,
i get the error i stated in the title when i try to fetch something from an api,
when i check with postman with the same url i get a valid jason,
the request comes back with a status of 200 so its fine on that end.
howerver when i execute the following command the error occurs:
fetch('/api/bug',{mode:'no-cors'}).then(response => response.json())
.then(data => console.log(data));
the Json:
{
"_id" : "abc123",
"title" : "Cannot save ",
"description" : "problem ",
"severity" : 1,
"createdAt" : 154210735954,
"creator" : {"nickname" : "Nick"}
}
Edit:
After changing from Json To Text,
The fetch request returns the html of the page, and the postman request return a json, any reason for this?

Axios | VueJS | Laravel | Post Request Not able to access Object

So I'm attempting to send my post data to my controller and then access it via a object. It definitely passes the data but for some reason wont let me access any of the items with in that object its really weird.
Here is my post request in the vue component.
axios.post('/users', {user: this.user})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
});
Here is what I have in my controller and as I said I do get the user info but I cant access it such as doing $user->id, but when I just do $user I can see the user data including the id.
//Here we get all the users info from the Axios Vue.
$user = $request->get('user');
return response()->json([
'status' => 'success',
'msg' => $user->id,
], 201);
The error I get is a php error as I can is it under the network response area and this is what the error message says.
"message": "Trying to get property 'id' of non-object"
But when I just do this in the controller.
//Here we get all the users info from the Axios Vue.
$user = $request->get('user');
return response()->json([
'status' => 'success',
'msg' => $user,
], 201);
It returns a 201 and shows this in the msg.
{"id":1,"email":"test#test.com","full_name":"John Doe","first_name":"John","last_name":"Doe","is_active":1,"overide_login":1,"skill_id":5,"phone":null,"shifts_id":0,"bilingual":0,"full_time":0}
Am I formatting the Object wrong or something?... It would be great if someone could help because I really don't understand why this does not work.
ALSO NOTE EVERYTHING IS ON THE NEWEST RELEASES OF VUEJS/AXIOS AND LARAVEL.
You have to decode it first, please add this into your controller.
$input = ($request->all() == null ? json_decode($request->getContent(), true) : $request->all());
echo $input['user']['id']
Hope this works for you.

Json::decode returns NULL

I have problem with Json::decode. I'm using this code:
use Drupal\Component\Serialization\Json;
$client = \Drupal::httpClient();
$request = $client->post($rest_url, [
'form_params' => [
'id' => $rest_id,
],
]);
$response = Json::decode($request->getBody());
to get JSON from some server but it returns NULL. Of course this is just a part of the code (without try, catch...)
$request->getBody() return is ok, but in Json::decode I'm still getting NULL.
The only thing I noticed is that in Postman, when I look at raw body content, I see some empty lines at the beginning of the JSON (like return on keyboard when typing), but I checked JSON as it is on JSONLint and it's valid.
Any idea what is the problem?
I'm not familiar with Drupal's JSON serializer, but try to force response body conversation to a string.
$response = Json::decode($request->getBody()->getContents());
Guzzle return a Stream object from getBody(), it could be the issue.

Is there an easy way to make GORM errors restful api friendly

I'm working on a simple Restful API in GRAILS, I want users to be able to create an entry on one of my domain classes, so they can hit an entry point /rest/v1/create/event?params
In the receiving controller if the GORM entry fails, !event.save()
I have code like this:
def result = [
'status' : 'error',
'data' : event.errors.fieldErrors.toList()
]
render result as JSON
Is there a way to easily make event.errors.fieldErrors JSON friendly, something with just the field error and message, or will I have to write a parser method to handle this?
Ending up writing a short method to parse through and make friendly errors
If anyone finds this useful, here it is:
def gorm_errors(results) {
results = results.fieldErrors.toList()
def errors = []
for(error in results) {
errors.add([
'type' : 'invalid_entry',
'field' : error.field,
'rejected_value' : error.rejectedValue,
'message' : error.defaultMessage
])
}
return errors
}
Here is a more "groovy-er" version of the above example:
def gorm_errors(errors) {
errors.fieldErrors.toList().collect {error ->
[
'type': 'invalid_entry',
'field': error.field,
'rejected_value': error.rejectedValue,
'message': error.defaultMessage
]
}

YII - Adding error code in form validation

I have a web-service and want to send a custom error-code and string in case form validation fails. We can specify error 'message' in form validation rules, but I want to add a numerical error code, that I can use later to get a text string. Extending CValidator is not an option as I want to use standard validators.
Ideally, I would like something like this in my rules() function.
array('page', 'numerical', 'integerOnly' => true, 'min' => 1, 'message' => '{attribute} is invalid', 'code' => 10079),
Later I return a JSON block like
{
'code': 10079,
'message' : 'page is invalid'
}
I am thinking of attaching a behavior to validators, but not quite able to figure out a way to make it work. Is there any other yii-way to do it?
instead of message , you just return the error code as message and on the view page just call a function to retrieve the appropriate error message.
provide $form->error(); as parameter to get errorMessage on the view page.