Laravel 返回 text/html 而不是 json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42837126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:34:47  来源:igfitidea点击:

Laravel return text/html and not json?

laravellaravel-5laravel-5.2

提问by uzhas

I have this in response headers:

我在响应头中有这个:

Response headers (165 B)    
    Host    
    "localhost:8000"
    [Learn More]
    Connection  
    "close"
    [Learn More]
    Content-Type    
    "text/html; charset=UTF-8"
    [Learn More]
    Date    
    "Thu, 16 Mar 2017 14:33:53 GMT"
    [Learn More]
    Transfer-Encoding   
    "chunked"

My controller is quite simple:

我的控制器很简单:

public function login(Request $request){

      return response()->json([
        'name' => 'Abigail',
        'state' => 'CA'
        ]);
    }

Im using angular for post.

我使用 angular 进行发布。

回答by Hiren Makwana

Laravel provides modify header information using Responseclass.

Laravel 使用Response类提供修改头信息。

Try this way in your controller :

在您的控制器中尝试这种方式:

$contents = View::make('embedded')->with('foo', $foo);
$response = Response::make($contents, $statusCode);
$response->header('Content-Type', 'text/plain');
return $response;

回答by Serge

Laravel returns json by default if you don't return a view... Have you tried

如果不返回视图,Laravel 默认返回 json ......你有没有试过

return ['name' => 'Abigail', 'state' => 'CA'];