ThinkPHP6.0部署相关问题

目录
  1. 1. 跨域失败解决方法
  2. 2. nginx 配置
  3. 3. 通过模版向前端的script标签内传递数组

跨域失败解决方法

在应用的app/middleware.php文件中添加跨域中间件

1
2
3
4
5
6
<?php
// 应用中间件定义
return [
// 全局中间件
app\middleware\AllowCrossDomainCustom::class,
];

app\middleware\AllowCrossDomainCustom.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

declare(strict_types=1);

namespace app\middleware;

use think\Response;

class AllowCrossDomainCustom
{
public function handle($request, \Closure $next)
{
// 如果是预检请求,直接返回
if ($request->method(true) === 'OPTIONS') {
return Response::create('', 'json', 200)
->header([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, X-Requested-With,X-Token',
'Access-Control-Allow-Credentials' => 'true',
]);
}

// 正常请求走下一个中间件
$response = $next($request);

// 给正常响应加上 CORS 头
$response->header([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, X-Requested-With,X-Token',
'Access-Control-Allow-Credentials' => 'true',
]);

return $response;
}
}

nginx 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
server {
listen 80;
server_name datacenter.test;

root C:/code/dataCenter/public;
index index.php index.html index.htm;

# 静态文件处理
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}

# 主要请求处理 - 关键部分!
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
break;
}
try_files $uri $uri/ =404;
}

# PHP处理
location ~ \.php$ {

# windos 下 nginx 配置
include php/php-7.4.conf;

# Linux 下 nginx 配置
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}

# 安全设置
location ~ /\.(ht|git) {
deny all;
}

autoindex off;
}

通过模版向前端的script标签内传递数组

1
2
3
4
5
6
7
8
9
10
11
12
<script type="module">
import { mixins } from "./static/js/mixin.js";
const phpOjb = `{:json_encode($phpOjb)}`;
new Vue({
el: '#app',
mixins: [mixins],
data() {
return {
obj: JSON.parse(phpOjb),
};
}
})