我在一个项目目录中使用 laravel 和 Vue JS 构建了一个基于 API 的应用程序。我使用 jwt auth 系统进行登录,这个包:php-open-source-saver/jwt-auth
现在,我想从 ajax 请求调用此路由在我的应用程序之外:
http://127.0.0.1:3000/automation/get_data/sdfd
为此,我在 web.php 文件中添加了此路由:
Route::get('/automation/get_data/{param1?}/{param2?}', [Automation::class, 'get_data']);
而
get_data
类的Automation
方法是这样的:
public function get_data ( Request $request ) {
$user = Auth::user();
echo '<pre>';
var_dump( $user );
echo '</pre>';
echo 'get data method : access the data like this : <br/>';
echo '<pre>';
print_r($request->route('param1'));
print_r($request->route('param2'));
echo '</pre>';
}
Ajax请求:
const accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNzE1ODM4OTQ1LCJleHAiOjE3MTU4NDI1NDUsIm5iZiI6MTcxNTgzODk0NSwianRpIjoiOVAzM0FvYVBDZjBKbjhzUiIsInN1YiI6IjEiLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.Xx1bZXI808PKMzsKJFblY2WKSmDX2_ioC1oIvYjHaGo';
const url = 'http://127.0.0.1:3000/automation/get_data/sdfd';
const headers = new Headers({
'Authorization': `Bearer ${accessToken}`
});
fetch(url, {
method: 'GET',
headers: headers,
mode: 'no-cors' // Add this line
})
.then(response => {
if (!response.ok) { // Check for successful response status code
throw new Error(`API request failed with status ${response.status}`);
}
return response.json(); // Convert to JSON
})
.then(data => {
console.log("Received data from API:", data);
// Access data properties here (e.g., data.user_id, data.message, etc.)
})
.catch(error => {
console.error("Error:", error);
// Handle errors based on error type (network, response status, etc.)
});
但是我没有得到任何回应,在控制台中我可以看到:
index.html:33 Error: Error: API request failed with status 0
at index.html:24:15
我的总体目标是从应用程序外部调用该路由,并在 get_data 方法中显示记录的用户详细信息。
你能告诉我该怎么做吗?
您必须配置
config/cors.php
文件以允许必要的来源和方法:
return [
'paths' => ['api/*', 'automation/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://127.0.0.1:3000'], // Add your specific origin here
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
确保您的路由使用 JWT 中间件来验证请求。更新您的
web.php
文件:
Route::middleware(['api', 'jwt.auth'])->group(function () {
Route::get('/automation/get_data/{param1?}/{param2?}', [Automation::class, 'get_data']);
});
Your Controller
public function get_data(Request $request)
{
$user = Auth::user();
return response()->json([
'user' => $user,
'param1' => $request->route('param1'),
'param2' => $request->route('param2')
]);
}
Your Ajax
<script>
const accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNzE1ODM4OTQ1LCJleHAiOjE3MTU4NDI1NDUsIm5iOiIxNzE1ODM4OTQ1LCJqdGkiOiI5UDMzQW9hUENmMEpuOHNSIiwic3ViIjoiMSIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.Xx1bZXI808PKMzsKJFblY2WKSmDX2_ioC1oIvYjHaGo';
const url = 'http://127.0.0.1:3000/automation/get_data/sdfd';
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
})
.then(response => {
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
return response.json();
})
.then(data => {
console.log("Received data from API:", data);
})
.catch(error => {
console.error("Error:", error);
});
</script>