yracnet / vite-plugin-api-routes

Create API routes from path directory like to Nextjs
MIT License
29 stars 4 forks source link

CORS policy error #19

Closed vbo75 closed 9 months ago

vbo75 commented 9 months ago

Hi, I've got a React frontend fetching (with Axios) an API configured with your plug-in. I've got this error when I run dev :

Access to XMLHttpRequest at 'http://localhost:3000/api/login' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I search a lot on the web, change vite.config to :

server: {
    cors: {
      origin: 'http://localhost:3000',
      methods: ['GET', 'POST'],
      allowedHeaders: ["Content-Type", "Authorization"],
      preflightContinue: true      
    }

No changes. I found this post on stackoverflow.com that seems close to my issue but I don't know how I can enable CORS on the Express server as described.

Thanks.

leaftail1880 commented 9 months ago

Hello, You can use path to custom configure.ts file in your vite config

export default defineConfig({ 
  plugins: [ 
    pluginAPIRoutes({ 
      configure: "src/server/configure.ts", 
      ...
    }) 
  ]
)};

and then add to the src/server/configure.ts the following:

import express from "express";
import { ServerHook, ViteServerHook } from "vite-plugin-api-routes/model";

export const serverBefore: ServerHook = (server) => {
    server.use(express.json());
    server.use(express.cors()); // <- here
    server.use(express.urlencoded({ extended: true });
};

export const viteServerBefore: ViteServerHook = (server) => {
    serverBefore(server)
};
vbo75 commented 9 months ago

Thanks, it works !

Here the complete src/server/configure.js (with npm i cors) :

import express from "express";
import cors from "cors";

export const serverBefore = (server) => {
    server.use(express.json());
    server.use(cors()); 
    server.use(express.urlencoded({ extended: true }));
};

export const viteServerBefore = (server) => {
    serverBefore(server)
};