Try   HackMD

PHP語法在.JS檔中無法運作問題(以csrf為例)

在前端頁面要傳送表單到後端通常要經過驗證(@csrf)
由JS傳送則需要以下指令將csrf_token加入formdata
formdata.append('_token', ' {{ csrf_token() }}')
這是在blade.php中,可以讀到指令
但如果JS分離成.JS檔
將無法辨識PHP語法
所以要將指令下在blade.php中
再帶入JS

方法如下

  1. <head>裡面加上
    <meta name="csrf-token" content="{{ csrf_token() }}">
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  2. 在JS中宣告
    let csrf = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
  3. 帶入formdata
    formdata.append('_token', csrf)
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
tags: laravel csrf JS