javascript - 向 Express JS 服务器发出 POST 请求时出错
问题描述
我在发出 POST 请求时遇到问题。我实际上是在尝试向本地机器上运行的 Express 服务器发出多个 POST 请求。浏览器显示错误“类型错误:尝试获取资源时出现网络错误”和“内容安全策略:页面的设置阻止了在http://localhost:3000/favicon.ico (“default-src”) 处加载资源。FaviconLoader .jsm:165:19 内容安全策略:页面的设置阻止了在 data:application/font-woff2;charset=utf-... (“default-src”) 处加载资源。”
这是我的 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(/[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>
服务器代码:
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();
});
解决方案
此错误是由于浏览器阻止了 CORS(跨域资源共享)。尝试运行命令chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
。一般来说,chrome 只允许共享同源的资源。您也可以在 Chrome 中查看禁用同源策略以寻求帮助。完成此操作后,我在我的机器上运行了您的代码,它运行正常。
如果这不起作用,您可以使用Polyfills。最流行的 Polyfill 是isomorphic-fetch。有关使用同构提取的文章可在此处获得:https ://medium.com/vinh-rocks/how-to-handle-networkerror-when-using-fetch-ff2663220435
推荐阅读
- c# - 没有远程桌面的 Winium 和 Jenkins
- typescript - 键入从对象中删除键
- ios - UIImageView 图像出现在我的故事板或运行时,但不是两者
- git - 如何使用 git filter-branch 将文件添加到特定提交?
- react-native - 如何在我的 react-native 应用程序中使用 fontawesome 灯光图标?
- excel - 取消选择/排除自动过滤器中条件的动态值
- r - R:使用 POSIXct 集合分配数据框列
- java - 直接从我的 android 应用程序发送 whatsapp 消息
- python - 每次脚本执行时重写文件但同时在python中追加
- ionic-framework - 使用 Mapbox 跟踪服务公司资产