為什么http://localhost:8080/login.html會報404
const?http=require('http')
const?url=require('url')
const?querystring=require('querystring')
const?fs=require('fs')
let?user={
????admin:?123456
}
http.createServer((req,res)=>{
????let?path,get,post
????if?(req.method=='GET'){
????????let?{pathname,query}=url.parse(req.url,true)
????????path=pathname
????????get=query
????????complete()
????}if?(req.method=='POST'){
????????let?arr=[]
????????req.on('data',buffer={
????????????
????????})
????????req.on('end',()=>{
????????????post=querystring.parse(Buffer.concat(arr).toString())
????????})
????????complete()
????}
????function?complete(){
????????if?(path=='/login'){
????????????res.writeHead(200,{
????????????????"content-type":"text/plain;charset=utf-8"
????????????})
????????????let?{username,password}=get
????????????if?(!user[username]){
????????????????res.end(JSON.stringify({
????????????????????????err:?1,
????????????????????????msg:?'用戶名不存在'
????????????????????})
????????????????)
????????????}else?if(user[username]!=password){
????????????????res.end(JSON.stringify({
????????????????????err:?1,
????????????????????msg:?'密碼錯誤'
????????????????????})
????????????????)
????????????}else{
????????????????res.end(JSON.stringify({
????????????????????err:?0,
????????????????????msg:?'登錄成功'
????????????????????})
????????????????)
????????????}
????????}else?if(path=='/reg'){
????????????res.writeHead(200,{
????????????????"content-type":"text/plain;charset=utf-8"
????????????})
????????????let?{username,password}=post
????????????if(user[username]){
????????????????res.end(JSON.stringify({
????????????????????err:?1,
????????????????????msg:?'用戶名已經存在'
????????????????????})
????????????????)
????????????}else{
????????????????res.end(JSON.stringify({
????????????????????err:?0,
????????????????????msg:?'注冊成功'
????????????????????})
????????????????)
????????????}
????????}else{
????????????fs.readFile(`www${path}`,(err,data)=>{
????????????????if?(err){
????????????????????res.end('404')
????????????????}else{
????????????????????res.end(data)
????????????????}
????????????})
????????}
????}
}).listen(8080)
2020-05-24
1、你得把你開發時的文件目錄結構發出來,不然沒法準確分析。
2、僅僅針對上述你提供的信息來分析的話,目測應該是文件目錄不對,需要核實兩點:
1)上述js文件同級目錄下是否存在“www”文件夾,且該文件夾下存在“login.html”文件(估計你不會犯這種低級錯誤)
2)你的電腦是MAC還是Windows,如果是MAC,因為其對目錄的解析跟Windows不同,你讀取文件時不能寫`www${path}`(學習過程中先寫個絕對路徑什么的就行)