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 错误请求 推荐人政策: 跨源时严格源
首先要检查Content-Type标头
出于开发目的,您可以使用以下命令在没有网络安全的情况下运行 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