Having problem deploying express server on vercel [404 page not found]
Asked Answered
V

6

8

I tried to deploy my express server on vercel to solve cors problem on my front code.

The problem is 404 error pops up when I enter the deployed page:

but it goes well when I try on localhost.

// vercel.json       
{
      "version": 2,
      "builds": [
        {
          "src": "./index.js",
          "use": "@vercel/node"
        }
      ],
      "routes": [
        {
          "src": "/(.*)",
          "dest": "/"
        }
      ],
      "rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
    }

//index.js
const express = require("express");
const cors = require("cors");
const axios = require("axios");

const app = express();

const PORT = process.env.PORT || 3000;
require("dotenv").config();

let corsOptions = {
  origin: ["http://localhost:3000", "https://humanscape-team5a.netlify.app"],
};

app.use(cors(corsOptions));

app.get("/", (req, res) => {
  const textQuery = req.query.searchText;
  const numOfRowsQuery = req.query.numOfRows;

  axios
    .get(
      "http://apis.data.go.kr/B551182/diseaseInfoService/getDissNameCodeList",
      {
        params: {
          sickType: 1,
          medTp: 2,
          diseaseType: "SICK_NM",
          searchText: textQuery,
          ServiceKey: process.env.KEY,
          numOfRows: numOfRowsQuery,
          _type: "json",
        },
      }
    )
    .then(response => res.send(response.data));
});

app.listen(PORT, () => {
  console.log(`Server running on ${PORT}`);
});

As it works on localhost, I guess it is kind of vercel setting problem. Any thoughts?

Volution answered 11/6, 2022 at 13:28 Comment(1)
did you ever figure this out?Deadhead
D
7

Not sure if you're still looking for a solution, but I did resolve this after some significant trial and error.

First and foremost, vercel seems to require an /api folder with an index.js file in it to work. Originally, I got confused because my index.js file was also used to start my server when working locally. Vercel is basically taking the place of whatever your server file is locally. You should still leave this for local testing, but you can basically ignore it when working with vercel.

In your /api/index.js file you will house your routes.

./api/index.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('../routes/index');

var app = express();

const whitelist = [
  '*'
];

app.use((req, res, next) => {
  const origin = req.get('referer');
  const isWhitelisted = whitelist.find((w) => origin && origin.includes(w));
  if (isWhitelisted) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization');
    res.setHeader('Access-Control-Allow-Credentials', true);
  }
  // Pass to next layer of middleware
  if (req.method === 'OPTIONS') res.sendStatus(200);
  else next();
});

const setContext = (req, res, next) => {
  if (!req.context) req.context = {};
  next();
};
app.use(setContext);

app.use('/', indexRouter);

module.exports = app;

and my vercel.json file is...

// vercel.json

{
   "version": 2,
   "builds": [
    {
        "src": "./index.js",
        "use": "@vercel/node"
    }
   ],
   "routes": [
    {
        "src": "/(.*)",
        "dest": "/"
    }
   ]
}

Not sure if this is helpful, but this worked for me. The big thing is nesting your index.js routes file in an api folder.

Deadhead answered 11/9, 2022 at 5:26 Comment(0)
V
3

The documentation says that node.js applications require an api/ folder in project root. This means that your index.js must be inside this folder. Important: if your index is named app.js must be renamed to index.js

Link say: "To deploy a serverless Node.js API, create a function in a .js file within the /api directory at the root of your project:"

Vascular answered 19/10, 2022 at 2:54 Comment(0)
M
3

It would help if you tried to render for the node app deployment. it works for me.

Note: I tried many times to deploy our node express app on Vercel but it didn't work. In Vercel not possible to have a server-run web app. Vercel is a cloud platform for static frontends and serverless functions.

Here is my app screenshort

Mccarthyism answered 21/3, 2023 at 20:19 Comment(0)
N
3

I had my a file named app.js instead of index.js

First I renamed this app.js to index.js ==> changing this worked for me.

package.json

...
  "scripts": {
    "start": "node index.js",
    "server": "nodemon index.js"
  },
...

vercel.json

{
    "version": 2,
    "builds": [
        {
            "src": "./index.js",
            "use": "@vercel/node"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "/"
        }
    ]
}

Northington answered 31/3, 2023 at 12:23 Comment(2)
This worked for me. Thanks.Tonsillotomy
@Tonsillotomy no problem my friend!Northington
L
1

First as stated above the main starting file should be inside "api" folder (api folder is in root ), name has to be changed to index.js if it is app.js , or index.ts if its in typescript.

And the configuration for vercel.json should be in root folder with this content:

{ "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }

It is always better to look for dedicated company documentation regarding any app deployment for recent changes. In case of express deployment on vercel, it is Vercel Documentation on express deployment

Legra answered 28/4, 2024 at 7:21 Comment(0)
M
0

Well in case you are new to coding and you don't quite understand all that they are saying this is for you:

the api folder is usually where your app.js file is. In most cases people use the /src folder.

So you first go to the app.js file and rename it to index.js file.

Next you go to the other files as well: vercel.json, package.json, etc and change all app.js to index.js. After you're all set, commit and push.

Delete your old vercel deployed project and then deploy as a new project. This time things should work work. USUALLY MOST PEOPLE ASSUME AFTER RENAMING AND PUSHING TO GITHUB VERCEL WILL AUTOMATICALLY PICK THE CHANGES. Doesn't work that way. You need to deploy a new project.

This is how i managed to resolve my issue.

Mellman answered 15/8, 2024 at 16:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.