我有问题=“从源“http://127.0.0.1:8000”访问“http://localhost:8000/admin/image-upload/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”
这是我的文件: // 创建.jsx
import AuthenticatedLayout from "../../Layouts/AuthenticatedLayout";
// import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
// import { faAdd } from '@fortawesome/free-solid-svg-icons';
import { useForm, Head } from "@inertiajs/react";
import FormPost from "./FormPost";
import { Sidebar } from "@/Components/Dashboard/Sidebar";
import HeaderAll from "@/Components/HeaderAll";
export function Create({ auth, categories }) {
const { data, setData, errors, processing, post } = useForm({
title: "",
status: "published",
content: "",
category_id: "",
image: null,
});
const submit = (e) => {
e.preventDefault();
post(route("posts.store"));
// setData("image", null);
};
return (
<>
<HeaderAll user={auth.user} />
<Head title="Creat-Post" />
<Sidebar />
{/* Content */}
<div className="w-full pt-20 px-4 sm:px-6 md:px-8 lg:ps-72">
<h1 className="app-page-title">Create Post</h1>
<div className="app-card app-card-account shadow-sm d-flex flex-column align-items-start">
<div className="app-card-header p-3 border-bottom-0">
<div className="row align-items-center gx-3">
<div className="col-auto">
<div className="app-icon-holder"></div>
</div>
<div className="col-auto">
<h4 className="app-card-title">Create New Post</h4>
</div>
</div>
</div>
<div className="app-card-body px-4 w-100">
<FormPost
data={data}
setData={setData}
errors={errors}
processing={processing}
onSubmit={submit}
categories={categories}
/>
</div>
</div>
</div>
{/* <ReactQuill theme="snow" /> */}
</>
);
}
export default Create;
这是我的“FormPost”中的 Ckeditor // Ckeditor.jsx
import { CKEditor } from "@ckeditor/ckeditor5-react";
// import { Link } from "@inertiajs/react";
import { ClassicEditor } from "@ckeditor/ckeditor5-editor-classic";
import { Bold, Italic, Underline } from "@ckeditor/ckeditor5-basic-styles";
import { Essentials } from "@ckeditor/ckeditor5-essentials";
import { Paragraph } from "@ckeditor/ckeditor5-paragraph";
import { SimpleUploadAdapter } from "@ckeditor/ckeditor5-upload";
import { Heading } from "@ckeditor/ckeditor5-heading";
import { Link, AutoLink } from "@ckeditor/ckeditor5-link";
import {
List,
ListProperties,
AdjacentListsSupport,
} from "@ckeditor/ckeditor5-list";
import { Font } from "@ckeditor/ckeditor5-font";
import { Title } from "@ckeditor/ckeditor5-heading";
import { Autoformat } from "@ckeditor/ckeditor5-autoformat";
import {
Image,
ImageCaption,
ImageResizeEditing,
ImageResizeHandles,
ImageToolbar,
ImageUpload,
} from "@ckeditor/ckeditor5-image";
import { Alignment } from "@ckeditor/ckeditor5-alignment";
// import MiniCssExtractPlugin from "mini-css-extract-plugin";
// const csrfToken = document
// .querySelector('meta[name="csrf-token"]')
// .getAttribute("content");
// const uploadUrl = `http://localhost:8000/admin/image-upload?_token=${csrfToken}`;
// const uploadUrl = "{{ route('image.upload') }}";
const uploadUrl = "http://localhost:8000/admin/image-upload/";
export default function Ckeditor({ data, setData }) {
return (
<>
<CKEditor
// className="ml-8"
editor={ClassicEditor}
config={{
plugins: [
Autoformat,
Paragraph,
Bold,
Italic,
Essentials,
Underline,
Image,
ImageUpload,
SimpleUploadAdapter,
Heading,
Link,
List,
ListProperties,
AdjacentListsSupport,
AutoLink,
ImageCaption,
ImageToolbar,
ImageResizeEditing,
ImageResizeHandles,
Font,
Title,
Alignment,
],
title: {
placeholder: "My custom placeholder for the title",
},
placeholder: "My custom placeholder for the body",
toolbar: [
"undo",
"redo",
"|",
"heading",
"|",
"bold",
"italic",
"underline",
"alignment",
"|",
"bulletedList",
"numberedList",
"|",
"fontSize",
"fontFamily",
"fontColor",
"fontBackgroundColor",
"|",
"toggleImageCaption",
"imageTextAlternative",
// "ckboxImageEdit",
"image",
"imageCaption",
"imageResizeEditing",
"imageResizeHandles",
"imageUpload",
"|",
"link",
],
list: {
multiBlock: false,
properties: {
styles: true,
startIndex: true,
reversed: true,
},
},
simpleUpload: {
uploadUrl: uploadUrl,
withCredentials: true,
// Headers sent along with the XMLHttpRequest to the upload server.
headers: {
"X-CSRF-TOKEN": document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content"),
Authorization: "Bearer <JSON Web Token>",
},
},
}}
tag="textarea"
data={data.content}
onChange={(_, editor) => {
const content = editor.getData();
setData("content", content);
}}
/>
</>
);
}
这是我的后端控制器 //ImageUploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageUploadController extends Controller
{
public function storeImage(Request $request)
{
if ($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName . '_' . time() . '.' . $extension;
$request->file('upload')->move(public_path('upload-image'), $fileName);
$url = asset('upload-image/' . $fileName);
return response()->json(['fileName' => $fileName, 'uploaded' => 1, 'url' => $url]);
// return redirect()->route('image.upload');
}
}
}
我在这里使用 Laravel 和 React JS,请帮我解决这个问题:)
我尝试过更改 Laravel 中的 Cors.php 例如这样:
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => **['http://localhost:8000'],**
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
在此代码上“ 'allowed_origins' => ['http://localhost:8000'],”
尝试使用 laravel-cors 包,它允许您使用 Laravel 中间件配置发送跨源资源共享标头。
这与以下问题相同: 如何在 Laravel 中启用 CORS?