【发布时间】:2022-01-28 04:11:15
【问题描述】:
我在 youtube 上做一个在线课程,我按照和那个人完全相同的步骤,当我遇到这个错误时,我什至一遍又一遍地重新观看相同的部分,试图在谷歌中找到,阅读了很多在 stackoverflow 和其他站点中存在相同的错误,但无法解决。我是初学者,我只是在学习,如果有人可以帮助我,我会很感激。我有那些可能是这个问题的 arquives:server.js、script.js、style.css
server.js
const http = require('http')
const fs = require('fs')
const path = require('path')
http.createServer((req, res) => {
const file = req.url === '' ? 'index.html' : req.url
const filePath = path.join(__dirname, 'public', file)
const extname = path.extname(filePath)
const allowedFileTypes = ['.html', '.css', '.js']
const allowed = allowedFileTypes.find(item => item == extname)
if(!allowed) return
fs.readFile(
filePath,
(err, content) => {
if(err) throw err
res.end(content)
}
)
}).listen(5000, () => console.log('Server is running'))
script.js
const ul = document.querySelector("ul")
const input = document.querySelector("input")
const form = document.querySelector('form')
function addElement({ name, url }) {
const li = document.createElement('li')
const a = document.createElement("a")
const trash = document.createElement("span")
a.href = url
a.innerHTML = name
a.target = "_blank"
trash.innerHTML = "x"
trash.onclick = () => removeElement(trash)
li.append(a)
li.append(trash)
ul.append(li)
}
function removeElement(el) {
if (confirm('Tem certeza que deseja deletar?'))
el.parentNode.remove()
}
form.addEventListener("submit", (event) => {
event.preventDefault();
let { value } = input
if (!value)
return alert('Preencha o campo')
const [name, url] = value.split(",")
if (!url)
return alert('formate o texto da maneira correta')
if (!/^http/.test(url))
return alert("Digite a url da maneira correta")
addElement({ name, url })
input.value = ""
})
style.css
@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@300;600&display=swap');
* {
box-sizing: border-box;
}
html {
font-size: 62.5%;
}
body {
font-family: 'Quicksand', sans-serif;
background: #7159c1;
}
.container {
width: 80%;
max-width: 400px;
margin: auto;
}
h1 {
text-align:center;
color: white;
font-size: 3.4rem;
}
input {
width: 100%;
padding: 8px 16px;
margin-bottom: 32px;
border-radius: 16px;
border: 1px solid #ccc;
outline: none;
font-size: 1.6rem;
font-weight:300;
}
ul {
background: white;
box-shadow: 0px 4px 8px -2px #00000033;
border-radius: 6px;
border: 1px solid #ddd;
padding: 16px;
font-size: 1.4rem;
}
li {
list-style: none;
display:flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #ddd;
}
a {
display: block;
color: #333;
text-decoration: none;
padding: 16px 0;
font-size: 1.8rem;
}
a:hover {
font-weight: bold;
}
li:first-child,
li:last-child {
border: none;
}
li span {
cursor:pointer;
}
【问题讨论】:
-
将
if(!allowed) return行更改为if(!allowed){return res.end()} -
将
if(!allowed) return更改为if(!allowed) { res.statusCode = 404; res.end(); return;},因为您需要为每个传入的http请求发送一些响应。 -
将
if(err) throw err更改为if(err) { console.log(err); res.statusCode = 404; res.end(); return;}。同样,始终向传入的 http 请求发送响应。
标签: javascript html css node.js