-1

I am facing problems in making a POST request. I am actually trying to make multiple POST requests to the Express server running on my local machine. The browser shows errors "TypeError: NetworkError when attempting to fetch resource" and "Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”). FaviconLoader.jsm:165:19 Content Security Policy: The page’s settings blocked the loading of a resource at data:application/font-woff2;charset=utf-… (“default-src”)."

Here's my JS code:

var email = $("#mail");
var password = $("#password");
var submit = $("#signup");
var form = $("#register");
var showPass = $("#showPass");
var confirmPassword = $("#confirmPass");
//var name = $("#name");
var emoji = $(".emoji");
window.onload = function() {
  email.val("");
  password.val("");
}
showPass.on("click", function() {
  $(this).is(':checked') ? password.attr('type', 'text') : password.attr('type', 'password');
  $(this).is(':checked') ? confirmPassword.attr('type', 'text') : confirmPassword.attr('type', 'password');
});
password.keyup(function() {
  var pswd = $(this).val();
  if (pswd.length < 8) {
    $('#length').removeClass('valid').addClass('invalid');
    emoji.eq(-1).text('❌').css('color', '#ec3f41');
  } else {
    $('#length').removeClass('invalid').addClass('valid');
    emoji.eq(-1).text('✔').css('color', 'green');
  }
  if (pswd.match(/[A-z]/)) {
    $('#letter').removeClass('invalid').addClass('valid');
    emoji.eq(0).text('✔').css('color', 'green');
  } else {
    $('#letter').removeClass('valid').addClass('invalid');
    emoji.eq(0).text('❌').css('color', '#ec3f41');
  }
  if (pswd.match(/[A-Z]/)) {
    $('#capital').removeClass('invalid').addClass('valid');
    emoji.eq(1).text('✔').css('color', 'green');
  } else {
    $('#capital').removeClass('valid').addClass('invalid');
    emoji.eq(1).text('❌').css('color', '#ec3f41');
  }
  if (pswd.match(/\d/)) {
    $('#number').removeClass('invalid').addClass('valid');
    emoji.eq(2).text('✔').css('color', 'green');
  } else {
    $('#number').removeClass('valid').addClass('invalid');
    emoji.eq(2).text('❌').css('color', '#ec3f41');
  }
}).focus(function() {
  $('#pswd_info').show();
}).blur(function() {
  $('#pswd_info').hide();
});
submit.on("click", async function() {
  if (email.val() === "" || !IsEmail(email.val())) {
    email.focus(function() {
      if (email.val() === "")
        email.css("box-shadow", "0 0 1px 1px red");
    });
    email.focusout(function() {
      if (email.val() !== "")
        email.css("box-shadow", "none");
    });
    form.get(0).reportValidity();
    return false;
  } else if (password.val() === "" || !isPassValid(password.val())) {
    password.focus(function() {
      if (password.val() === "" || !isPassValid(password.val()))
        password.css("box-shadow", "0 0 1px 1px red");
    });
    password.focusout(function() {
      if (isPassValid(password.val()))
        password.css('box-shadow', "none");
    });
    form.get(0).reportValidity();
    return false;
  } else if (confirmPassword.val() === "") {
    confirmPassword.focus(function() {
      if (confirmPassword.val() === "")
        confirmPassword.css("box-shadow", "0 0 1px 1px red");
    });
    confirmPassword.focusout(function() {
      if (confirmPassword.val() !== "")
        confirmPassword.css('box-shadow', "none");
    });
    form.get(0).reportValidity();
    return false;
  } else if ($("#name").val() === "") {
    $("#name").focus(function() {
      if ($("#name").val() === "")
        $("#name").css("box-shadow", "0 0 1px 1px red");
    });
    $("#name").focusout(function() {
      if ($("#name").val() !== "")
        $("#name").css('box-shadow', "none");
    });
    form.get(0).reportValidity();
    return false;
  } else if ($("#username").val() === "") {
    $("#username").focus(function() {
      if ($("#username").val() === "")
        $("#username").css("box-shadow", "0 0 1px 1px red");
    });
    $("#username").focusout(function() {
      if ($("#username").val() !== "")
        $("#username").css('box-shadow', "none");
    });
    form.get(0).reportValidity();
    return false;
  } else {
    //signup register
    //send a post request and store details in data base and then return to operatorLog.html

    const data = {
      email: email.val(),
      password: password.val(),
      name: $("#name").val(),
      username: $("#username").val()
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    };
    const response = await fetch('/api', options);
    const resp_data = await response.json();
    console.log(resp_data);
    // $.post('/api',data,function(json){
    //  console.log(json);
  }
});

function IsEmail(email) {
  var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if (!regex.test(email)) {
    return false;
  } else {
    return true;
  }
}

function isPassValid(password) {
  // if(password.len>=8 && password.match(/[A-z]/) && password.match(/[A-Z]/) && password.match(/\d/))
  //  return true;
  // else
  //  return false;
  if ($("#length").hasClass("valid") && $("#capital").hasClass("valid") && $("#number").hasClass("valid"))
    return true;
  else
    return false;
}
#name-label {
  margin-right: 50px;
}

#user {
  margin-right: 82px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Bus Man Sign Up</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" type="text/css" href="signin.css">
  <link rel="stylesheet" type="text/css" href="signup.css">
  <link rel="stylesheet" type="text/css" href="operatorLog.css">
  <link rel="stylesheet" type="text/css" href="operatorSignup.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;700&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Fredoka+One&family=Hammersmith+One&display=swap" rel="stylesheet">
  <link rel="shortcut icon" href="~/favicon.ico">
</head>

<body>
  <div class="navbar">
    <span><a href="index.html" id = "home">Bus Man <i class = "fa fa-bus"></i></a></span>
    <a href="help.html" id="help">Help</a>
    <!-- <select>
   <option>Cancel current booking</option>
   <option>Check booking status</option>
   <option>Reschedule</option>
  </select> -->
    <!-- <div class="dropdown">
            <button class="dropbtn">Manage Booking 
            <i class="fa fa-angle-down"></i>
            </button>
        <div class="dropdown-content">
            <a href="#">Current Booking</a>
        <a href="#">Cancel Booking</a>
        <a href="#">Reschedule</a>
     </div>
    </div>  -->
    <a href="operatorLog.html"> Login/Signup <i class="fa fa-user-circle" style = "font-size: 1.2em"></i></a>
  </div>

  <div class="form">
    <i class="fa fa-user-circle"></i>
    <div class="signin">
      <label id="email">Email:</label>
      <input type="email" name="email" placeholder="Eg. abc@xyz.com" form="register" id="mail" required>
      <br>
      <label id="pass">Password:</label>
      <input type="password" name="password" form="register" id="password" required>
      <div id="pswd_info">
        <h4>Password must meet the following requirements:</h4>
        <ul>
          <li id="letter" class="invalid"><span class="emoji">❌</span>At least <strong>one letter</strong></li>
          <li id="capital" class="invalid"><span class="emoji">❌</span>At least <strong>one capital letter</strong></li>
          <li id="number" class="invalid"><span class="emoji">❌</span>At least <strong>one number</strong></li>
          <li id="length" class="invalid"><span class="emoji">❌</span>Be at least <strong>8 characters</strong></li>
        </ul>
      </div>
      <br>
      <label id="confirm-pass-label">Confirm Password:</label>
      <input type="password" name="confirmPass" id="confirmPass" form="register" required>
      <br>
      <input type="checkbox" name="showPass" id="showPass" form="register"> Show Password
      <br>
      <label id="name-label">Agency Name:</label>
      <input type="text" name="name" id="name" form="register" required>
      <br>
      <label id="user">Username:</label>
      <input type="text" name="username" id="username" form="register" required>
      <br>
      <button id="signup" form="register" type="submit">Sign Up</button>
      <br>
    </div>
  </div>
  <form id="register" method="POST"></form>
  <div class="promise"></div>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script type="text/javascript" src="operatorSignup.js"></script>
</body>

</html>

Server Code:

const express = require('express');
const app = express();
// const favicon = require('serve-favicon');
const DataStore = require('nedb');
const cors = require('cors');
// const path = require('path');
app.use(express.static('public'));
app.use(express.json({limit:'1mb'}));
//app.use(express.urlencoded({extended:true}));
app.use(cors());
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.listen(3000, ()=> console.log('listening at 3000'));
const db_op = new DataStore('database_operator.db');
db_op.loadDatabase();
app.post('/',(req,res)=>{
 console.log("Got a request");
 console.log(req.body);
 const data = req.body;
 const timestamp = Date.now();
 data.timestamp = timestamp;
 // db.insert(data);
 // check if from and to are available and if available send all
 res.json({
  status:"success",
  from: data.from,
  to: data.to,
  date: data.date
 });
});
app.post('/api',(req,res)=>{
 console.log("Got a request from travel op");
 console.log(req.body);
 const data = req.body;
 const timestamp = Date.now();
 data.timestamp = timestamp;
 db_op.insert(data);
 res.status(200).end();
});
When I submit the form I get the above-mentioned errors. Please help!! It's really frustating!

4 Answers4

2

This error is due to blocking the CORS (Cross-Origin-Resource-Sharing) by the browser. Try running the command chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security . Generally, chrome allows the sharing of resources with the same origin only. You can see Disable same origin policy in Chrome for help too. I ran your code on my machine after doing this and it worked correctly.

If this does not work, you can use Polyfills. The most popular Polyfill is isomorphic-fetch. A article on using isomorphic fetch is availaible here: https://medium.com/vinh-rocks/how-to-handle-networkerror-when-using-fetch-ff2663220435

jsgrewal12
  • 138
  • 9
  • I have seen these articles but couldn't find them useful. The command you mentioned has been used by me but did not solve my problem. Can you provide some more detail regarding the approach to debug? – Karan Bhatia Jul 11 '20 at 11:14
2

You are making a request to /api. So you have not defined the exact domain here. In your case, it must be picking up the URL of your localhost:port on whatever hostname:port you are running your frontend code. You need to define exact http(s)://hostname:port/api to make it work.

Ankit Singh
  • 671
  • 6
  • 14
1

Actually the submit button is linked with the form so on submission the POST request goes to the localhost URL and not the API URL. Hence there was a problem in making a POST request to the server. I actually got it after long time.

0

Adding e.preventDefault() to your submit listener will prevent the form from submitting (through the localhost URL).

...
submit.on("click", async function(e) {
  e.preventDefault();

  // execute the rest of your code.
});
StefanN
  • 756
  • 5
  • 16