Hello there my website is on cpanel and when i make an api call it returns contnet-type html instead of json note that it worked perfectly on my localhost but for some reason it isn't working
Code
public function fetch_companies()
{
//getting company that is linked to coupon
$companies_id = Coupons::where('company_id' , '!=', 'null')->pluck('company_id');
$companies = Companies::whereIn('id' , $companies_id)->get();
return response()->json($companies);
}
i tried setting the headers to json like this
return response()->json($companies)->withHeaders([
'Content-Type' => 'application/json',
]);
but it didn't work
here is the link to my website you may test it using postman
http://coupon-app.epizy.com/company/api/fetch
just to put you in the picture the code currently running this page is this
public function fetch_companies()
{
//getting company that is linked to coupon
$companies_id = Coupons::where('company_id' , '!=', 'null')->pluck('company_id');
$companies = Companies::whereIn('id' , $companies_id)->get();
return response()->json($companies)->withHeaders([
'Content-Type' => 'application/json',
]);
}
if you need any information please comment and Thanks in Advance
well i found out that the cause of this problem was my server provider as you can find here
https://infinityfree.net/support/javascript-error-using-api-or-mobile-android-app/
it is a security "feature" although it is not a feature that blocks any request that doesn't accept cookies and run javascript
Change Accept & Content-Type to Application/json on the header
Related
I'm working on a blog like website and have being adding this rich text editor feature to it. This app is built with Vue for the front and Laravel, and this text editor is a dependency called vue-quill.
I use axios to post all the data and nothing more. Im using it to create posts with Raw html tags from this editor, it actually works fine creating and updating posts locally, but only fails on my server whenever you try to update any post, it returns empty response and status 200.
It does not happen when you create a post. Im not using any kind of image upload service but I'm using my own solution, which consists on transforming images from base 64 to file objects and then send them to a controller via axios. On update action it is similar but the images that were already uploaded on the post are fetched, then converted to base64 again and then converted to file objects again (in order to preserve previous images) for new images I convert them from base64 to file object as I do on my create action.
Here is the code I use to create from base 64 to file object :
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
And this would be my axios action:
axios
.post("/api/posts", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response)=>{
this.submit = false;
this.title= '';
this.showAlert("success", 'Post created successfully.' , '')
})
.catch((error) =>{
// etc
});
The formData object only store the raw html, images and a string, nothing more than that, but I'm not sure if the headers of the axios are ok, the laravel action is like this:
public function updatePost(Request $request)
{
$request->validate([
'files.*' => 'required|mimes:jpg,jpeg,png|max:2048'
]);
$post = Post::find($request->postId);
$images = $request->file('files');
// creamos el post primero
$post->title = $request->title;
$post->body = $request->body;
$post->save();
// the rest of the code for storing images
return response()->json(['post' => $post]);
I think something is preventing it to reach to this action, because the response is empty.
Edit: I had a problem later where the request was giving status 301, after searching here and there I found out that everything was okay but in the server. The host has to be configured as stated here in this quick guide for 301 troubles : https://medium.com/#mshanak/laravel-return-empty-response-690f8a308d9a.
So I'm having an interesting issue with Laravel HTTP Client while trying to hit an API endpoint for PayPal.
I can get Laravel HTTP Client working on all my endpoints that POST with data, but this one endpoint that only requires headers (no data is passed in the body) fails with an error.
{
"name":"INVALID_REQUEST",
"message":"Request is not well-formed, syntactically incorrect, or violates schema.",
"debug_id":"609388c4ddfe4",
"details":[
{
"field":"\/",
"location":"body",
"issue":"INVALID_SYNTAX",
"description":"MALFORMED_REQUEST_JSON"
}
],
"links":[
{
"href":"https:\/\/developer.paypal.com\/docs\/api\/orders\/v2\/#error-INVALID_SYNTAX",
"rel":"information_link",
"encType":"application\/json"
}
]
}
When I hit the same endpoint in Postman everything works fine
My method for hitting the endpoint looks like this
public static function capture($order)
{
$token = Paypal::fetchToken();
$api_url = config('services.paypal.api_url') . '/v2/checkout/orders/' . $order['id'] . '/capture';
$headers = [
'Content/Type' => 'application/json',
];
$response = Http::withToken($token)
->withHeaders($headers)
->post($api_url)
->json();
return $response;
}
I have tried passing an empty array in the post request like this ->post($api_url, []) but that did not work either.
I have hardcoded the $api_url just in case I made a mistake with my formatting with variables. Resulted in the same issue.
I have tried changing the 'Content/Type' in the header to 'none'. This did not work either and also doesn't make sense because I have this same header set in postman and it works fine (PayPal docs also says to pass this content/type)
Based on the error I am receiving I can only assume the request is hitting the endpoint correctly, but either the HTTP wrapper or guzzle itself is adding something to the body when I leave it blank and it is causing PayPal to throw the error. Don't really know what else I can try though.
Is there a parameter I am overlooking for specifying an empty body on a post request?
Any help is appreciated.
Looking at the source I found the following solution
$response = Http::withToken($token)
->withHeaders($headers)
->send("POST", $api_url)
->json();
I had the same issue, but I fixed it with a simple trick.
I found the solution on https://docs.guzzlephp.org/en/stable/request-options.html#json.
This code should work.
$response = Http::withToken($token)
->withHeaders($headers)
->post($api_url,['json' => []])
->json();
The empty array is now seen as an empty array/body in JSON.
$files = $request->file('images'); // return {}
$_FILES['images']; // return {"name":"sample-passport.jpg","type":"image\/jpeg","tmp_name":"D:\\xampp\\tmp\\php4AD9.tmp","error":0,"size":264295}
Have you tried to remove the Content-Type header? According to this Github issue, it seems to be a problem.
So, I set up a new Laravel installation to test this out and it's working fine on my side. Of course, there's no authorisation whatsoever but this shouldn't impact the result too much.
routes/api.php
Route::post('/profile/upload_image', function (Request $request) {
dd($request->file('image'));
});
Postman configs
Your post input attribute type change file after upload you will get a response.enter image description here
I am currently working in codeigniter and I am new to this.
I was wondering how to retrieve the JSON values using API call .
Can anyone suggest me where should I start.
Many Thanks in advance
Pass your array of row to json_encode();example for method of controller is below
public function getUserList() {
header('Content-Type: application/json');
$query = $this->db->get('mytable');
if(count($query) > 0) {
$message = array('status' => 'true' , 'message' => 'Record get successfully' , 'data' => $return );
}else{
$message = array('status' => 'false' , 'message' => 'Record not found.' );
}
echo json_encode($message);
}
Codeigniter does not have an inbuilt HTTP method so you need to use other things in php to achieve this.
There are 2 ways, you can use cURL, but honestly... it's convoluted... but read this: http://php.net/manual/en/book.curl.php
Another method is using stream_context_create() http://php.net/manual/en/function.stream-context-create.php
I strongly suggest using this 2nd one as its much easier to work with (in context with curl..
Much of how you setup your request depends on the API you are referencing with and the kind of requests it allows: GET, POST ... and what kind of header information it requires you to send over as well do they require oAuth header?
There is no 1 bunch of code fits all, I had to create a full custom library to integrate codeigniter into Magento, it took many hours.
I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!