【发布时间】:2021-07-10 14:02:50
【问题描述】:
我有一个基本网站,但遇到了问题。我对此非常陌生,似乎无法修复它。
当我运行服务器并浏览到 http://localhost:3000/class/create 时,一切正常。但是,当我尝试添加学生时,我在浏览器上收到一条消息,上面写着
“无法 POST /api/create”和控制台中的 404 错误。
应该发生什么:控制台记录“创建学生条目”
index.js
const express = require('express')
const app = express()
// loading body-parser
const bodyParser = require('body-parser')
// loading our routers
const mainRouter = require('./mainRoutes.js')
const classRouter = require('./classRoutes.js')
// tell Express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// mounting the routers
app.use('/', mainRouter)
app.use('/class', classRouter)
app.listen(3000)
console.log('Express server running on port 3000')
classRoutes.js
const path = require('path')
const express = require('express')
const router = express.Router()
const classList = [] // our class list array
router.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'class', 'index.html'))
})
router.get('/create', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'class', 'create.html'))
})
// RESTful api
router.get('/api/list', function (req, res) {
res.json(classList) // Respond with JSON
})
router.get('/api/get/:id', function (req, res) {
res.json(classList[req.params.id]) // Notice the wildcard in the URL?
// Try browsing to /api/get/0 once you've added some entries
})
router.post('/api/create', function (req, res) {
console.log('creating a student entry')
})
module.exports = router
create.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Class List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action="/api/create" method="post">
<div>
<label for="studentName">Enter The Student's Name:</label>
<input type="text" id="student" name="student">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
Chrome 开发工具输出(网络标签)
【问题讨论】:
-
没有回应
-
@Nicolas对不起?
-
执行请求时,Chrome 开发工具中的“网络”选项卡有什么作用?
-
@zishone 我在尝试请求时附加了开发工具输出
-
因为那个位置没有路线。
标签: javascript html node.js express routes