2

我正在尝试构建一个支持 Laravel API 的 React 应用程序,因此基本上使用通配符路由进行客户端路由,然后简单地使用 API 路由组来处理数据。

这是我的routes/web.php文件:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/payment/redirect/{orderId}', ['as' => 'mollie.redirect', 'uses' => 'Controller@index']);
Route::get('/{any}', ['as' => 'index', 'uses' => 'Controller@index'])->where('any', '.*');

这是我的routes/api.php文件:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('/orders', ['as' => 'orders.store', 'uses' => 'OrdersController@store']);
Route::post('/payment/webhook', ['as' => 'mollie.webhook', 'uses' => 'OrdersController@webhook']);

这导致:

在此处输入图像描述

但是,每当我尝试提出请求时,POST api/orders这就是我在 Postman 中得到的:

在此处输入图像描述

哪个Controller@index应该响应,而不是OrdersController@store应该是 JSON 响应。

这是我的OrdersController代码:

<?php 

namespace Http\Controllers;

use Customer;
use Http\Requests\OrderCreateRequest;
use Order;
use Product;
use Services\CountryDetector;
use Services\LanguageService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;

class OrdersController extends Controller
{
    const ERROR_PRODUCT_COUNTRY_UNAVAIALBLE = 'errors.products.country_unavailable';

    public function store(OrderCreateRequest $request, LanguageService $language, Order $orders, Customer $customers, Product $products)
    {
        $customer = $customers->firstOrCreate(['email' => $request->input('customer.email')], [
            'name' => $request->input('customer.fullname'),
            'email' => $request->input('customer.email'),
            'phone' => $request->input('customer.phone'),
            'country' => $language->getCurrentCountry(),
            'company_name' => $request->input('customer.company_name'),
            'city' => $request->input('customer.city'),
            'optin_newsletter' => $request->input('customer.newsletter')
        ]);

        $product = $products->find($request->input('cart.product_id'));

        $pricing = $product->getCountryPrice($language->getCurrentCountry());

        if (! $pricing)
        {
            return response()->json([
                'error' => trans(self::ERROR_PRODUCT_COUNTRY_UNAVAILABLE, ['productName' => $product->name])
            ], 422);
        }

        $order = $orders->create([
            'customer_id'        => $customer->id,
            'product_id'         => $product->id,
            'product_flavor'     => $request->input('cart.flavor'),
            'amount'             => $pricing->amount,
            'vat_amount'         => $pricing->vat_amount,
            'currency'           => $pricing->currency,
            'carehome_selection' => $request->input('carehome.custom'),
            'carehome_name'      => $request->input('carehome.name'),
            'carehome_type'      => $request->input('carehome.type'),
            'carehome_address'   => $request->input('carehome.address'),
            'carehome_city'      => $request->input('carehome.city'),
            'carehome_notes'     => $request->input('carehome.notes'),
            'custom_message'     => $request->input('gifting_options.message'),
            'is_anonymous'       => $request->input('gifting_options.anonymous'),
            'wants_certificate'  => $request->input('gifting_options.certificate'),
            'status'             => Order::STATUS_PENDING,
            'type'               => $request->input('payment_type')
        ]);

        $mollie = $order->getOrCreateMollie();

        return response()->json([
            'mollie_redirect' => $mollie->getCheckoutUrl()
        ]);
    }
}

另外,如果我尝试暂时删除 API 路由,但仍然尝试访问它们,我会很奇怪地得到一个 404,这意味着 Laravel 能够检测到该路由,但它使用了错误的控制器响应。

我该如何解决?

4

4 回答 4

2

我已经尝试像上面建议的那样设置两个标题,但它对我不起作用。相反,我修改了路由正则表达式以匹配不以开头的 urlapi并且它有效:

Route::view('/{any?}', 'app')
->where('any', '^(?!api).*');
于 2019-01-17T20:02:26.253 回答
1

与@Marcin Nabialek 所说的类似,这是应该与请求一起发送的标头之一的问题。然而,它不是,Content-Type而是Accept

您必须使用Accept: application/json才能接收 API 的 JSON 响应,至少在 Laravel 5.7.6 中是这样的。

于 2018-10-02T08:38:46.727 回答
0

首先 - 当您删除 api 路由时,方法没有路由POST(因为您的通配符“catch-all”路由仅适用于GETorHEAD请求)。这就是为什么您会收到 HTTP 404 - 找不到此请求的路由。

如果您按照问题中的描述添加 api 路由 - 提供的响应似乎是原始树枝视图(可能是布局)。我假设您三重检查了 OrdersController 不会以这种方式响应 - 如果没有,请尝试添加return '{}';为控制器的第一行,看看会发生什么。

无论如何 - 它可能与请求类型有关(您将请求标头设置为application/x-www-form-urlencoded) - RouteServiceProvider 或api中间件可能与它有关。尝试将请求标头设置application/json为例如,并深入研究 RouteServiceProvider 和 api 中间件。

于 2018-10-01T12:33:44.947 回答
0

我认为这里是两件事的混合:

  • 你没有在这里设置Content-Typeapplication/json所以应用程序“认为”这个正常的形式被发送
  • 您使用自定义验证类OrderCreateRequest,可能验证失败。这就是为什么如果你放入dd('test');你的控制器方法它根本不会被执行

如果验证失败,验证器会抛出ValidationException异常并实现在这种情况下发生的情况如下所示:

protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
    if ($e->response) {
        return $e->response;
    }

    return $request->expectsJson()
                ? $this->invalidJson($request, $e)
                : $this->invalid($request, $e);
}

因此,如果它是 AJAX 请求或 Content-Type 设置为application/json(或多或少),那么它将返回验证失败的 JSON 响应,否则会进行重定向。

于 2018-10-01T17:53:54.860 回答