请求方法:POST 状态代码:400 错误请求引用策略:跨域时严格源

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


import { Restaurant } from "@/types"
import { useAuth0 } from "@auth0/auth0-react"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

export const useCreateMyRestaurant = () => {
    const{ getAccessTokenSilently} = useAuth0()
    
    const createMyRestaurantRequest = async(restaurantFormData:FormData):
    Promise<Restaurant> => {
        const accessToken = await getAccessTokenSilently()

        const response = await fetch(`${API_BASE_URL}/api/my/restaurant`,{
            method: 'POST',
            headers:{
                Authorization: `Bearer ${accessToken}`,
                
            },
            body:restaurantFormData,
        })
        console.error(response)
        if (!response.ok){
            
            throw new Error("Failed to create restaurant")
        }
        return response.json()
    }

    const {
        mutateAsync:createRestaurant,
        isPending,
        isSuccess,
        error,
    } = useMutation({mutationFn:createMyRestaurantRequest})

    if(isSuccess){
        toast.success("Restaurant Created")
    }

    if(error){
        toast.error("Unable to update restaurant")
    }
    return{createRestaurant,isPending}
}



import {Request, Response} from "express"
import Restaurant from "../models/restaurant"
import cloudinary from "cloudinary"
import mongoose from "mongoose"

const getMyRestaurant = async ()=> {}

const createMyRestaurant = async(req:Request, res:Response) =>{
    
    try {
        const existingRestaurant = await Restaurant.findOne({user:req.userId})
        if(existingRestaurant){
            return res.
            status(409)
            .json({message:"User restaurant already exist"})
        }
        const image = req.file as Express.Multer.File
        const base64Image = Buffer.from(image.buffer).toString("base64")
        const dataURI = `data:${image.mimetype};base64,${base64Image}`

        const uploadResponse = await cloudinary.v2.uploader.upload(dataURI)

        const restaurant = new Restaurant(req.body)
        restaurant.imageUrl = uploadResponse.url
        restaurant.user = new mongoose.Types.ObjectId(req.userId)
        restaurant.lastUpdated = new Date()
        await restaurant.save()
        res.status(201).json({message:"Restaurant created successfully"})
    } catch (error) {
        console.log(error)
        res.status(500).json({message:"Something went Wrong"})
    }
}

export default {
    createMyRestaurant
}


在邮递员中它运行顺利,但是在我制作前端之后,错误是

请求方法:POST 状态代码:400 错误请求引用策略:跨域时严格源 请求网址: http://localhost:7000/api/我的/餐厅 请求方式: 邮政 状态代码: 400 错误请求 推荐人政策: 跨源时严格源

javascript reactjs typescript react-hooks
1个回答
0
投票

首先要检查Content-Type标头

  • 在 POST 请求中发送 FormData 时,Content-Type 标头 不应手动设置为 application/json 或其他任何内容, 浏览器自动将其设置为 multipart/form-data
  • 确保您的服务器上正确配置了 CORS 以接受 来自前端来源的请求
  • 由于您使用 Multer 来处理文件上传,请确保正确填充 req.file,如果未定义,文件可能无法正确到达您的服务器

出于开发目的,您可以使用以下命令在没有网络安全的情况下运行 chrome:

macOS

open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials

Windows

start chrome --user-data-dir="%TMP%\temporary-chrome-profile-dir" --disable-web-security --disable-site-isolation-trials

Linux

google-chrome --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
© www.soinside.com 2019 - 2024. All rights reserved.