Laravel API返回HTML获取请求

发布于 2025-02-13 03:43:37 字数 791 浏览 1 评论 0原文

我正在尝试这样做:

Route::get('/foo', function (Request $request) {
    return response()->json('Ready');
});

我得到答案html :(

但是帖子是有效的:

Route::post('/bar', function (Request $request) {
    return response()->json('Ready');
});

结果:“准备”

是什么问题? 谢谢。

编辑: 好的。我使用VUE 3和VUE-ROUTER,因此我更改了文件web.php :(

Route::get('/{any?}', function () {
return view('index'); })->where('any', '.*');

要工作spa)

然后我更改为

Route::get('/', function () {
return view('index'); 
})

现在get request works!

但是,如果没有此代码,Vue-Router无法正常工作。

Route::get('/{any?}', function () { return view('index'); })->where('any', '.*');

我应该怎么办 ?谢谢。

I'm trying to do it:

Route::get('/foo', function (Request $request) {
    return response()->json('Ready');
});

I get an answer HTML :(

But POST is works:

Route::post('/bar', function (Request $request) {
    return response()->json('Ready');
});

result: "Ready"

What could be the problem?
Thx.

EDIT:
ok. I use Vue 3 and Vue-router, so i changed the file web.php:

Route::get('/{any?}', function () {
return view('index'); })->where('any', '.*');

(to work SPA)

Then I changed to

Route::get('/', function () {
return view('index'); 
})

Now the GET request works!

But Vue-router can't work properly without this code.

Route::get('/{any?}', function () { return view('index'); })->where('any', '.*');

What should I do ? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北恋 2025-02-20 03:43:37

问题是您使用的是Web.php而不是API.PHP路由文件。
默认情况下,将Web.php的所有闭合路由都解析为可渲染的对象,该对象将输出渲染到HTML。
如果您确实使用api.php,则将封闭路线解析为JSONRESPONSE。

总而言之,请使用api.php进行json响应和web.php或仅查看响应(又称渲染值)。

最后,应该在文件末尾设置您的vue-router解析器。

Route::get('/{any?}', function () {
    return view('index'); })->where('any', '.*');
});

强烈建议您:

// All of your other routes here...

Route::view("/{any?}", "index")->where("any", ".*");

The problem is that you are using web.php instead of api.php routing file.
By default all closure routes from web.php are parsed to Renderable object, which renders the output to a HTML.
If you do use api.php the closure routes will be parsed to a JsonResponse.

In summary, please do use the api.php for json responses and web.php or views only responses (aka. renderables).

Finally your vue-router parser from laravel router should be set at the end of the file.

You have

Route::get('/{any?}', function () {
    return view('index'); })->where('any', '.*');
});

I strongly recommend:

// All of your other routes here...

Route::view("/{any?}", "index")->where("any", ".*");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文