search

Home  >  Q&A  >  body text

API not found in vercel deployment

I have deployed my web application on vercel using github. The frontend is loaded, but api requests from the frontend are not found with 404. By the way, this is a MERN app This is my vercel.json

{
    "buildCommand": "cd client && npm install && ./node_modules/vite/bin/vite.js build",
    "outputDirectory": "client/dist",
    "framework": "vite",
    "rewrites": [
        {
            "source": "/api/(.*)",
            "destination": "/index.js"
        }
    ]
}

This is index.js

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const cookieParser = require('cookie-parser');
const router = require('./router/router');
const setupCronJob = require('./cron');
const fs = require('fs');
require('dotenv').config();

const app = express();
app.use(express.json());
app.use(cookieParser());    // for reading cookies
const allowedOrigins = ['http://127.0.0.1:5173','https://cozy-stay.vercel.app'];
const corsOptions = {
    credentials: true,
    origin: allowedOrigins,
    methods: 'GET, POST, PUT, DELETE',
    allowedHeaders: 'Content-Type, Authorization, Cookie'
};

app.use(cors(corsOptions));

const port = process.env.PORT || 4000;

mongoose.set("strictQuery", false);

mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    serverSelectionTimeoutMS: 10000,
}).then(()=> {
    console.log('Connected to database')
}).catch(err=>{
    throw err;
})
setupCronJob();
app.use('/api',router);
app.listen(port);

This is the directory img

The frontend is already available but the api is not working properly, I think the api is not loaded yet. Please help me

P粉495955986P粉495955986289 days ago395

reply all(1)I'll reply

  • P粉541551230

    P粉5415512302024-01-30 00:48:05

    What currently seems to be happening is that https://cozy-stay.vercel.app/api the path request goes to the frontend server instead of the backend server as you expect:

    Request URL: https://cozy-stay.vercel.app/api/all-places
    Request Method: GET
    Status Code: 404 
    Remote Address: 76.76.21.9:443
    Referrer Policy: strict-origin-when-cross-origin

    Fix01

    You can use two vercel applications for frontend and backend:

    • cozy-stay.vercel.app
    • cozy-stay-backend.vercel.app - Use this as the backend server host in your frontend application.

    Fix02

    You can run a load balancer that sends all requests with the /api prefix to the backend and other requests to the frontend. The IDK vercel platform supports this feature.

    reply
    0
  • Cancelreply