如何运行简单PhpAPI?
How to run simple Php API?
我为 API 使用了 Php Slim Framework。我将 Slim Framework 安装到我服务器上的 web 根目录并复制我编码的 index.php 文件。
Index.php:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->run();
function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
}
catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
?>
我收到 500(内部服务器错误)。
编辑:我更改了“$app = new Slim();”到“$app = new \Slim\Slim();”然后收到以下错误。
我正在使用 EasyEngine(Nginx)。
Edit-2:现在 500 Internal 消失了,但显示了另一个错误。
XMLHttpRequest cannot load http://api.mangayurdu.com/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://deneme.mangayurdu.com' is therefore not allowed access.
这是我获取 JSON 数据的代码:
.factory('MY', function($http){
var factory = {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
从发布的代码来看,Slim 似乎无法找到名为 getUser
的函数。 getUsers()
在您的代码中定义,但没有 getUser()
函数。
尝试将其放在 PHP 页面的开头
<?php header('Access-Control-Allow-Origin: *');?>
我为 API 使用了 Php Slim Framework。我将 Slim Framework 安装到我服务器上的 web 根目录并复制我编码的 index.php 文件。
Index.php:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->get('/user/:id', 'getUser');
$app->run();
function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
}
catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
?>
我收到 500(内部服务器错误)。
编辑:我更改了“$app = new Slim();”到“$app = new \Slim\Slim();”然后收到以下错误。
我正在使用 EasyEngine(Nginx)。
Edit-2:现在 500 Internal 消失了,但显示了另一个错误。
XMLHttpRequest cannot load http://api.mangayurdu.com/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://deneme.mangayurdu.com' is therefore not allowed access.
这是我获取 JSON 数据的代码:
.factory('MY', function($http){
var factory = {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
从发布的代码来看,Slim 似乎无法找到名为 getUser
的函数。 getUsers()
在您的代码中定义,但没有 getUser()
函数。
尝试将其放在 PHP 页面的开头
<?php header('Access-Control-Allow-Origin: *');?>