I nearly find the way, how to implenment the REST Style in Zend Framework 2.
But my doubt is, the methods like get(), getList() is working fine, but the update() method id not calling and showing the following error in the html page.
HTML PAGE:
$.ajax({
url: 'http://128.199.233.137/api/v1/tes/74',
data: {"gender":"1","country":"1"},
type: 'PUT',
success: function(result) {
console.log(result);
// Do something with the result
}
});
OPTIONS http://233.102.233.137/api/v1/tes/74 jquery-2.1.3.js:8625 jQuery.ajaxTransport.sendjquery-2.1.3.js:8161 jQuery.extend.ajaxput.html:16 (anonymous function)jquery-2.1.3.js:4430 jQuery.event.dispatchjquery-2.1.3.js:4116 jQuery.event.add.elemData.handle
put.html:1 XMLHttpRequest cannot load http://233.102.233.137/api/v1/tes/74. Invalid HTTP status code 405
MY controller is:
<?php
namespace Tes\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
use Zend\Http\Response;
class TesController extends AbstractRestfulController
{
//getAction
public function get($id) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
$resp = array("method" => "Get", "id" => $id);
return new JsonModel($resp);
}
//updateAction
public function update($id, $data) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
$resp = array("method" => "Update", "id" => $id, "data" => $data);
return new JsonModel($resp);
}
}
Related
I keep getting the error message:
{message: '(#200) Provide valid app ID', type: 'OAuthException', code: 200,...
I can get the HTTP Get response with curl and by entering the URL, but when trying to use the exact same url in the Javascript SDK, i am getting the error told before.
Following is my JS script.
var pageAccessToken = 'APP_ID|CLIENT_ID';
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('https://connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId : 'APP_ID',
xfbml : true,
version : 'v13.0'
});
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{"url":"https://graph.facebook.com/v13.0/instagram_oembed?url=INSTAGRAMURL&access_token=" + pageAccessToken},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
});
Any ideas?
My app is live (I can get the correct information from HTTP Get)
EDIT:
As CBroe said i changed my code to the following and it now works.
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{
"url":"INSTAGRAMURL",
access_token: pageAccessToken
},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
So having both the parameters inside the {} works. I originally tried with 2 {}, which didn't work.
However, CBroe, as can be seen in facebook docs: https://developers.facebook.com/docs/facebook-login/guides/access-tokens
I can use the Client_ID in javascript.
Addition - After i wrote it in PHP (with the PHP SDK for facebook), to resolve having the Client ID readable in JS:
<?php
require_once __DIR__ . '/assets/src/Facebook/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => 'APP-ID',
'app_secret' => 'APP-Secret',
'default_graph_version' => 'v13.0'
//'default_access_token' => '{access-token}', // optional
]);
/* PHP SDK v5.0.0 */
/* make the API call */
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get(
'/instagram_oembed?url=INSTAGRAMURL',
'APP-ID|APP-ID_or_Client-ID'
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$Node = $response->getDecodedBody();
echo <<< EOF
<div class=""InstagramResults">
EOF;
print_r($Node["html"]);
echo <<< EOF
</div>
EOF;
?>
´´´
You are trying to send a instagram_oembed endpoint URL, to the instagram_oembed endpoint. The url parameter should only be the INSTAGRAMURL.
And if you have to pass a different access token than what the SDK will use internally, then that needs to be passed as an additional parameter to the endpoint.
Note that you should not expose your client_id (actually, the app secret) in publicly available client-side code ever though. Everyone could steal it from there, and would have a valid app access token for your app.
I did with yii2 an acess token authorization if the access token is valid it works fine, but if the access token is invalid it returns the following CORS problem
Access to XMLHttpRequest at 'server' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
if the token is expired, the server works fine storing the old token on another table etc, but the client still gets the same CORS problem
I don't understand why it only happens when I try to return a 401 response, but it works when the acces token is valid, any idea?
This is the code I think its relevant
BehaviorsConfig.php
public static function corsFilterConfig($metodos_aceptados)
{
return [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Allow-Origin' => ['*'], // Añadido
'Access-Control-Request-Method' => $metodos_aceptados,
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => false,
'Access-Control-Max-Age' => 86400,
],
];
}
public static function authenticatorConfig()
{
return [
'class' => QueryParamAuth::className(),
'except' => ['options'],
'tokenParam' => 'access_token',
];
}
every controller
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = BehaviorsConfig::corsFilterConfig(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
$behaviors['authenticator'] = BehaviorsConfig::authenticatorConfig();
return $behaviors;
}
and now to check if the token is still valid and not expired I did this function
public function beforeAction($action){
if(AccessService::isExpired()){
throw new HttpException(401, "Sesión expirada, vuelva a conectarse.");
}
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
I have the following named route with params, to which I want to redirect from a post request:
Route::get('/view-project-team/{project_request_id}', 'SinglePageController#viewProjectTeam')->name('view.project.team');
The controller where I handle the post request:
public function createProjectTeam(Request $request){
try {
$projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);
TeamMember::whereIn('email', $request->projectTeamEmails)
->update([
'project_request_id' => $projectRequest->id
]);
$projectTeam = TeamMember::get();
/*return response()->json( [
'success'=> true,
'projectRequestId' => $projectRequest->id
]);*/
return redirect()->route('view.project.team', ['project_request_id' => $projectRequest->id ]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'project team creation failed'];
}
}
And the response that I get:
In the network tab, I see 90 under Name, which obviously stands for the id and only when I hover over I see the full URL http://team-management-tool.test/view-project-team/90
It is so weird as it seems correct the way i use the redirect, no clue what can be the issue then?
I am creating API in SLIM in which i have included two routes files customers.php and books.php. books.php route file is working properly but when i run customers.php routes it says 404 error.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../src/config/db.php';
$config = [
'settings' => [
'displayErrorDetails' => true,
//'determineRouteBeforeAppMiddleware' => true,
'debug' => true
],
];
$app = new \Slim\App($config);
//$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
// Customer routes
require '../src/routes/customers.php'; //this route file does not work
require '../src/routes/books.php'; //this route file work
$app->run();
My app is creating a new entry via a POST request in an api end point.
Now, if any validation is failed then instead of returning an error json, laravel 5.3 is redirecting the request to home page.
Here is my controller:
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization);
}
If there is no issue with validation then the entity will be successfully added in the database, but if there is issue with validating the request then instead of sending all the error messages as a json response it redirects back to the home page.
How i can set the validate return type to json, so with every request if the validation failed then laravel will send all the error messages as json by default.
You can do your validation as:
$validator = \Validator::make($request->all(), [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422)
}
The validation used in the question looks as per the recommendation by laravel. The reason of redirection is that it throws an exception which you can easily catch using the code below. So it's better to use the recommended way of code instead of re-writing framework's code again :)
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
try {
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
} catch (ValidationException $e) {
return response()->json($e->validator->errors(), 422);
}
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization, 201);
}