【问题标题】:Cannot GET /index.html无法获取 /index.html
【发布时间】:2021-12-26 04:23:19
【问题描述】:

我的项目目录是-

app
├── app.js
├── index.html
├── node_modules
├── package.json
├── package-lock.json
├── signup_success.html
└── style.css

我的应用文件代码如下-

app.js 文件代码:-

var express=require("express");
var bodyParser=require("body-parser");

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/gfg');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
    console.log("connection succeeded");
})

var app=express()


app.use(bodyParser.json());
app.use(express.static('public'));
//app.use(express.static(__dirname + "/../public"));
//app.use(app.router);
app.use(bodyParser.urlencoded({
    extended: true
}));

app.post('/sign_up', function(req,res){
    var name = req.body.name;
    var email =req.body.email;
    var pass = req.body.password;
    var phone =req.body.phone;

    var data = {
        "name": name,
        "email":email,
        "password":pass,
        "phone":phone
    }
db.collection('details').insertOne(data,function(err, collection){
        if (err) throw err;
        console.log("Record inserted Successfully");
            
    });
        
    return res.redirect('signup_success.html');
})


app.get('/',function(req,res){
res.set({
    'Access-control-Allow-Origin': '*'
    });
return res.redirect('index.html');
}).listen(3000)


console.log("server listening at port 3000");

当我运行 app.js 文件时,我在浏览器上得到“Cannot GET /index.html”? enter image description here

【问题讨论】:

    标签: javascript html node.js web


    【解决方案1】:

    您指定 express.static 来提供静态 html 文件。查找快速静态文档here

    app.use(express.static('public'));
    

    您将 express.static 指向一个名为“public”的文件夹。有一个公用文件夹来存储所有静态文件是一种常见的做法。创建一个public/ 文件夹并将您的 .css 和 .html 文件移动到那里。

    【讨论】:

    • 我收到消息“无法获取 /index.html”,因为我没有提供 HTML 文件的正确路径。现在解决它后,我的项目目录看起来像这样- app ├── app.js ├── node_modules ├── package.json ├── package-lock.json └── public ├── index.html ├── signup_success .html └── style.css 谢谢我已经解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-06-11
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多