2022年1月20日 星期四

跨域CORS心得

環境

寶塔
nginx 1.21.1
三個項目:
test.win.bt(主項目)
api.win.bt(API接口)
api2.win.bt(laravel接口)


test.win.bt/api/ 代理 api.win.bt

https://stackoverflow.com/a/16158558  nginx proxy_pass 404 error, don't understand why

test.win.bt nginx配置文件

server
{
    server_name test.win.bt;

    location /api/ {
        proxy_pass http://api.win.bt/;
    }
    ...
    #PHP-INFO-START
    include php/80.conf;
    #PHP-INFO-END
    ...
}


http://test.win.bt/api/

打開(index.php),可以正常顯示json內容

但是 http://test.win.bt/api/index.php (任何.php訪問)卻是404

https://stackoverflow.com/a/65867308  Nginx Reverse Proxy returns 404 for PHP
原因是 include php/80.conf; 在C:\BtSoft\nginx\conf\vhost\test.win.bt.conf 和 C:\BtSoft\nginx\conf\vhost\api.win.bt.conf 重複被引用了,把 test.win.bt.conf 的 include php/80.conf; 註解掉即可。(註解api.win.bt.conf 的無效)
但是這樣解就造成 test.win.bt 下面無法跑php


(註解 include php/80.conf;  前)靜態json文件 http://test.win.bt/api/test.json  可以訪問

但是如果是ajax 用post請求會返回405
原因:
https://cloud.tencent.com/developer/article/1680056  Nginx的405 not allowed错误解决

Access-Control-Allow-Origin

加在 nginx

https://ubiq.co/tech-blog/enable-cors-nginx/  How to Enable CORS in NGINX
server
{
    server_name api.win.bt;
    add_header Access-Control-Allow-Origin *;
    ...
}


add_header 對500無效

https://serverfault.com/a/431580  Nginx services fails for cross-domain requests if the service returns error
所以如果 http://api.win.bt/json.php 返回了500錯誤,即使在nginx加了 add_header Access-Control-Allow-Origin *;  。瀏覽器還是會報CSRF錯誤




PHP手動返回500錯誤

https://stackoverflow.com/a/1555877  How can I get php to return 500 upon encountering a fatal exception?
header("HTTP/1.1 500 Internal Server Error");

加在php中

https://stackoverflow.com/a/7564919  how to bypass Access-Control-Allow-Origin?
不指定域名
header('Access-Control-Allow-Origin: *');
指定域名
header('Access-Control-Allow-Origin: http://test.win.bt');

test.win.bt/api2/ 代理 api2.win.bt

server
{
    server_name test.win.bt;

    location /api2/ {
        proxy_pass http://api2.win.bt/;
    }
    ...
}

http://test.win.bt/api2/test

routes/web.php
Route::any('/test', function () {
    return [1,2,3];
});


但是 laravel的web路由會檢查CSRF token(VerifyCsrfToken),所以報419錯誤

所以改用api的路由

http://test.win.bt/api2/api/test

routes/api.php
Route::any('/test', function (Request $request) {
    return [1,2,3];
});

即可正常請求

因為laravel的偽靜態把index.php 幹掉了,所以不存在 http://test.win.bt/api/*.php 的404問題。當然 http://test.win.bt/api2/api/*.php 還是會404的
location / {  
try_files $uri $uri/ /index.php$is_args$query_string;  
}








2022年1月8日 星期六

scoop 和nvm 使用心得

安裝scoop

scoop是 Windows 軟件管理器
需使用 Windows PowerShell 安裝
PS C:\Users\user> iwr -useb get.scoop.sh | iex
For example, to set the execution policy to 'RemoteSigned' please run :
'Set-ExecutionPolicy RemoteSigned -scope CurrentUser'

如果Windows PowerShell報錯中文亂碼

https://superuser.com/a/653716  How do I change my cmd.exe to English?
使用 chcp 可以查當前的code,然後切換成英文
C:\Users\user> chcp 437
Active code page: 437

如果報錯則執行

PS C:\Users\user> Set-ExecutionPolicy RemoteSigned -scope CurrentUser
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): Y

再試一次

PS C:\Users\user> iwr -useb get.scoop.sh | iex
Initializing...
Downloading scoop...
Extracting...
Creating shim...
Downloading main bucket...
Extracting...
Adding ~\scoop\shims to your path.
'lastupdate' has been set to '2022-01-08T20:48:03.5639640+08:00'
Scoop was installed successfully!
Type 'scoop help' for instructions.

測試

PS C:\Users\user> scoop help
Usage: scoop <command> [<args>]

Some useful commands are:

alias       Manage scoop aliases
bucket      Manage Scoop buckets
cache       Show or clear the download cache
cat         Show content of specified manifest.
checkup     Check for potential problems
cleanup     Cleanup apps by removing old versions
config      Get or set configuration values
create      Create a custom app manifest
depends     List dependencies for an app
export      Exports (an importable) list of installed apps
help        Show help for a command
hold        Hold an app to disable updates
home        Opens the app homepage
info        Display information about an app
install     Install apps
list        List installed apps
prefix      Returns the path to the specified app
reset       Reset an app to resolve conflicts
search      Search available apps
status      Show status and check for new app versions
unhold      Unhold an app to enable updates
uninstall   Uninstall an app
update      Update apps, or Scoop itself
virustotal  Look for app's hash on virustotal.com
which       Locate a shim/executable (similar to 'which' on Linux)

Type 'scoop help <command>' to get help for a specific command.

如果安裝時報SSL錯誤

可能是你IE版本太舊,在 Windows PowerShell 嘗試使用以下命令解決
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

安裝社區提供的 bucket

https://sspai.com/post/52710  给 Scoop 加上这些软件仓库,让它变成强大的 Windows 软件管理器
(可以在git bash裡執行)
$ scoop bucket add dorado https://github.com/h404bi/dorado
Checking repo... ok
The dorado bucket was added successfully.

scoop的目錄就是裝在 ~/scoop
~/scoop
$ ls
apps/  buckets/  shims/

安裝APP

scoop install dorado/<App 名>
$ scoop install dorado/redis-desktop-manager

查已安裝的APP

$ scoop list
Installed apps:

  7zip 21.07 [main]
  redis-desktop-manager 2021.10 [dorado]

使用scoop安裝nvm

$ scoop install main/nvm

$ nvm -v
Running version 1.1.9.
...

因為我的nodejs是官網msi安裝檔裝的,實際測試使用scoop 安裝的nvm無法切換新的nodejs版本,所以移除scoop安裝的nvm
$ scoop uninstall nvm

為什麼要安裝nvm

https://stackoverflow.com/a/64820435  Is there any way to fix package-lock.json lockfileVersion so npm uses a specific format?
因為兩個不同開發者用了不同版本的nodejs(14/16)和npm在同一個項目,造成新版本nodejs在npm install 時package-lock.json會產生 "lockfileVersion": 2 


安裝nvm

https://github.com/nvm-sh/nvm  Node Version Manager
預設安裝到 C:\Users\user\AppData\Roaming\nvm ,會偵測到系統的nodejs 目錄 C:\Program Files\nodejs
安裝完設定環境變量

然後就能正常切換nodejs版本
$ node -v
v14.17.5

安裝nodejs 16

$ nvm install 16
Downloading node.js version 16.13.1 (64-bit)...
Extracting...
Complete
Installation complete. If you want to use this version, type
nvm use 16.13.1

$ nvm list
    16.13.1
  * 14.17.5 (Currently using 64-bit executable)

$ nvm use 16.13.1

$ node -v
v16.13.1