-1

I am trying to send an HTTP request from my React app to my local server on a different port. However, every time I send a POST HTTP request, this error happens:

CORS Error

This is the code I have in my React app:

 const handleSubmit = async (e) => {
    e.preventDefault();
    const data = {ingredientInput};
    console.log(data.ingredientInput);
    console.log(JSON.stringify(data));
    const response = await fetch('http://localhost:5000/verify', {
        method: 'POST',
        
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify(data),
    });

This is the code I have in my server.

const express = require('express');
const router = express.Router();
let bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use((req, res, next) => {
    res.append('Access-Control-Allow-Origin', '*');
    res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.append('Access-Control-Allow-Headers', 'Content-Type');
    next();
})

const PORT = 5000;

const app = express();

app.use(express.json());
const fs = require('fs');

app.post('/verify', (req, res) => {
    console.log(req.body);
})

I have added the headers that the browser states such as the 'Access-Control-Allow-Origin' header but the CORS error still happens. Would anyone be able to tell me what the issue is?

Richard Silva
  • 33
  • 1
  • 4

1 Answers1

-1

You need to use the router.

app.use('/', router);
Ouyang Chao
  • 129
  • 3