Slim框架中的访问控制源

时间:2018-12-06 10:21:53

标签: php cors slim

更新索引中的此代码,但我无法访问此结果方法。

$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');});


$app->post('/result', function () use ($app) {

$roll_no = $app->request->post('roll_no');  
$db = new DbOperation();
$response = array();
if ($db->result($roll_no)) {
    $student = $db->getStudentR($roll_no);
    $response['error'] = false;       
    $response['student_name'] = $student['student_name'];

} else{
    $response['error'] = true;
    $response['message'] = "Invalid username or password";
}
echoResponse(200, $response);});

谢谢。 如何获得苗条的方法?

1 个答案:

答案 0 :(得分:0)

您不运行您的方法。另外,您还必须保留响应对象:

$app->post('/result', function (RequestInterface $request, ResponseInterface $response) use ($app) {

$roll_no = $app->request->post('roll_no');  
$db = new DbOperation();
$result= array();
if ($db->result($roll_no)) {
    $student = $db->getStudentR($roll_no);
    $result['error'] = false;       
    $result['student_name'] = $student['student_name'];

} else{
    $result['error'] = true;
    $result['message'] = "Invalid username or password";
}
$response->getBody()->write(json_encode($result));
return $response;});

$app->run();

您应该可以如下运行:

your-domain.com/result