CORS on react request to node.js API

Viewed 45

This is my node,js API,that works with no problems using postman, but when I try to make a request from a different origin like a react project the request is blocked

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 9000;
const routes  = require('./routes/routes');
const token = require('./config/config');
const cors = require('cors')

app.use(cors())
app.use(express.json());
app.use('/api', routes);

app.listen(port, () => console.log('server listening on port', port));
const url = "mongodb://localhost/titles_db";

mongoose.connect(url,{})
    .then( () => console.log('DB connected'))
    .catch( (e) => console.log('Erorr on db connection')); 

and this is the function that is called on my request

searchTitles = (req, res) => {
    const terms = req.query.terms;
    const format = req.query.format;

    titleSchema.find({title: {$regex:terms, $options: 'i'}})
        .then( data => {
            if(format == 'json')
                res.json(data);
            else{
                res.setHeader("Content-Type", "text/plain");
                res.send(data);
            } 
        })
        .catch( error => res.json( {message: error}))
}

and here is the function that makes the request on the frontend

const getFieldText = e => {
    setTerm({term: e.target.value });
    const url = `http://localhost:9000/api/titles/?terms=${e.target.value}&format=json`
    
    fetch(url)
      .then(response => console.log(response))
      .then(data => console.log(data));
  }

even including cors library on node

const cors = require('cors')

app.use(cors())

I get this response

Response { type: "cors", url: "http://localhost:9000/api/titles/?terms=aaaaaa&format=json", redirected: false, status: 403, ok: false, statusText: "Forbidden", headers: Headers, body: ReadableStream, bodyUsed: false }

I added an options array but I have the same result

var corsOptions = {
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }

app.use(cors(corsOptions))
1 Answers

configure the cross headers like this (in your server node config):

app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', "http://localhost:8080");

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, authorization, Access-Control-Allow-Origin');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  // Pass to next layer of middleware
  next();
});
Related