API not found in vercel deployment
P粉495955986
P粉495955986 2024-01-29 11:41:22
0
1
385

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粉495955986
P粉495955986

reply all(1)
P粉541551230

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!