Headers not persisted well

The code for my backend server clearly allows access to the frontend in the index.js:

require("dotenv").config();

const express = require('express');
const chalk = require('chalk');
const bodyParser = require('body-parser');
const http = require("http")
const app = express();
const port = process.env.PORT || 8000;

const cors = require('cors');

const corsOptions = {
  origin: process.env.CLIENT || 'http://localhost:3000',
  methods: 'GET,PUT,POST,DELETE',
  allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
  credentials: true
};

app.use(cors(corsOptions));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const server = http.createServer(app);

server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

require('./router')(app);

My frontend, which is a react app also hosted on frontend is not able to send requests to this backend:

Access to XMLHttpRequest at '{backend route}' from origin '{frontend domain}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have double checked the value of process.env.CLIENT which is the same as the frontend website URL. (https://{myappname}.vercel.app)

Here is my vercel.json:

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

UPDATE: I just noticed that certain endpoints work on the backend while some don’t. This is abnormal

If you’re having trouble deploying an Express app, this guide can help.

You can also ask v0 for suggestions tailored to your own project setup.

The issue has been resolved, I had an incomplete vercel.json file. Here is the correct one if someone gets stuck in future:

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

Thanks for sharing, @rungtavaidik! :smiley:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.