如何从 Nuxt JS 和 Symfony api 上传文件而不出现任何 CORS 错误

问题描述 投票:0回答:1

我正在尝试从 Nuxt3 前端和 Symfony 后端上传文件。但我收到这个错误

从源“http://localhost:8060”获取“http://localhost:8070/upload-book”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:确实如此没有 HTTP 正常状态。

let file = ref<File | null>();

const onSelectFile = (event: any): void => {
  file.value = event.target.files[0];
}

const onSaveBook = () => {
  try {
    if (!file.value) return;

    const formData = new FormData();
    formData.append('file', file.value);

    fetch('http://localhost:8070/upload-book', {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '*',
      },
      body: formData,
    })

  } catch (error) {
    console.log(error);
  }
#[Route('/upload-book', name: 'app_upload_book', methods: ['POST'])]
public function newBook(Request $request): JsonResponse
{
   $file = $request->files->get('file');

    if ($file) {
        $fileName = uniqid() . '.' . $file->getClientOriginalExtension();
        $file->move($this->getParameter('kernel.project_dir') . '/public/uploads', $fileName);

        return new JsonResponse('File uploaded successfully', Response::HTTP_OK);
    }

    return new JsonResponse('No file uploaded', Response::HTTP_BAD_REQUEST);
}
php vue.js symfony cors nuxt.js
1个回答
0
投票

接下来你应该更改你的 PHP 代码:

#[Route('/upload-book', name: 'app_upload_book', methods: ['POST', 'OPTIONS'])]
public function newBook(Request $request): JsonResponse
{
    $file = $request->files->get('file');

    if ($file) {
        $fileName = uniqid() . '.' . $file->getClientOriginalExtension();
        $file->move($this->getParameter('kernel.project_dir') . '/public/uploads', $fileName);

        return new JsonResponse('File uploaded successfully', Response::HTTP_OK, [
            'Access-Control-Allow-Origin' => '*',
        ]);
    }

    return new JsonResponse('No file uploaded', Response::HTTP_BAD_REQUEST, [
        'Access-Control-Allow-Origin' => '*',
    ]);
}

如您所见,我添加了

OPTIONS
方法,因为它是您的错误中的预检请求方法。并添加标头以允许来自任何远程的 CORS。

© www.soinside.com 2019 - 2024. All rights reserved.