简体   繁体   English

向 Express JS 服务器发出 POST 请求时出错

[英]Getting error in making POST request to Express JS server

I am facing problems in making a POST request.我在发出 POST 请求时遇到问题。 I am actually trying to make multiple POST requests to the Express server running on my local machine.我实际上正在尝试向在我的本地计算机上运行的 Express 服务器发出多个 POST 请求。 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”)."浏览器显示错误“TypeError: NetworkError when attempt to fetch resource”和“Content Security Policy: The page's settings blocked of a resource loading at http://localhost:3000/favicon.ico (“default-src”).FaviconLoader .jsm:165:19 内容安全策略:该页面的设置阻止了在 data:application/font-woff2;charset=utf-…(“default-src”)加载资源。”

Here's my JS code:这是我的 JS 代码:

 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(/[Az]/)) { $('#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(/[AZ]/)) { $('#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(/[Az]/) && password;match(/[AZ]/) && 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! 真是郁闷啊!

This error is due to blocking the CORS (Cross-Origin-Resource-Sharing) by the browser.此错误是由于浏览器阻止了 CORS (Cross-Origin-Resource-Sharing)。 Try running the command chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security .尝试运行命令chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security Generally, chrome allows the sharing of resources with the same origin only.通常,chrome 只允许共享同源资源。 You can see Disable same origin policy in Chrome for help too.您也可以在 Chrome 中查看禁用同源策略以获得帮助。 I ran your code on my machine after doing this and it worked correctly.这样做后我在我的机器上运行了你的代码并且它工作正常。

If this does not work, you can use Polyfills .如果这不起作用,您可以使用Polyfills The most popular Polyfill is isomorphic-fetch .最流行的 Polyfill 是isomorphic-fetch A article on using isomorphic fetch is availaible here: https://medium.com/vinh-rocks/how-to-handle.networkerror-when-using-fetch-ff2663220435此处提供了一篇关于使用同构获取的文章: https://medium.com/vinh-rocks/how-to-handle.networkerror-when-using-fetch-ff2663220435

You are making a request to /api .您正在向/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.在您的情况下,它必须在运行前端代码的任何主机名:端口上获取本地主机:端口的 URL。 You need to define exact http(s)://hostname:port/api to make it work.您需要定义确切的http(s)://hostname:port/api才能使其工作。

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.实际上提交按钮与表单链接,因此在提交时 POST 请求转到本地主机 URL 而不是 API URL。因此向服务器发出 POST 请求时出现问题。 I actually got it after long time.经过很长时间我才真正明白了。

Adding e.preventDefault() to your submit listener will prevent the form from submitting (through the localhost URL).e.preventDefault()添加到您的提交侦听器将阻止表单提交(通过本地主机 URL)。

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

  // execute the rest of your code.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM