Search code examples
node.jsreactjsherokumysqljs

how to disable fetch API to send OPTIONS request with Content-Type header?


I have a problem with my API. When I use fetch from ReactJS to send un json to NodeJS server, The server crashes...

fetch call :

 const jso = JSON.stringify({
        username: this.state.username,
        password: this.state.password
      })
      fetch("URL/authentication", {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: jso,
      }).then(res => res.json()).then((result) => {
        this.setState({
          answer: result.answer
        })

      }, (error) => {
        this.setState({isLoaded: true, error});

      })
  }

Here is the back-end side

var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser')
var mysql = require("mysql");

//Enabeling all Access-Control-Allow-Origin
app.use(cors());
app.options('*', cors())

var port = process.env.PORT || 5000

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//omitted mysql connections details

app.post('/authentication', (req, res) **=> {
    email = req.body.username,
    password = req.body.password,
    matching = "false"
    var dbpassword

    sql = "SELECT password FROM users WHERE email = ?";
    db.query(sql, email, (err, result, fields) => {
        if(err) {
            console.error('error query: ' + err.stack)
            return;
        }
        dbpassword = result[0].password;

         if(dbpassword === password){
        matching = "true";
        console.log(dbpassword + " : " + password);
        } 
        res.send({answer: matching});

    });
})

app.listen(port, function(){
    console.log("app running");
})

The thing is that this makes my server (hosted on Heroku) crash everytime I do a request from the front-end...

However, when I try to remove the header part from teh front end, the server doesn't crash but doesn't return anything...

After looking at the logs, I found that, when fetch has the header part with 'Content-Type': 'application/json', it sends an OPTIONS request before the post request...

My question : How can I make this to work? I tried a post request from postman and it works so I know that my server / algorithm is not the problem. Also, the server for the back-end is Heroku


Solution

  • I forgot to handle when my front-end doesn't send any request...

    This is maybe not perfect but it's working :

    app.post('/authentication', (req, res) => {
        email = req.body.username,
        password = req.body.password,
        matching = "false"
        var dbpassword
    
        if(email!=""){
    
            sql = "SELECT password FROM users WHERE email = ?";
            db.query(sql, email, (err, result, fields) => {
                if(err) {
                    console.error('error query: ' + err.stack)
                    return;
                }
                if(result.length > 0){
                    dbpassword = result[0].password;
    
                    if(dbpassword === password){
                    matching = "true";
                    console.log(dbpassword + " : " + password);
                    } 
                }
    
                res.send(JSON.stringify({answer: matching}));
            });
        }
    
        else res.send(JSON.stringify({answer: matching}));
    })