嗨,我正在阅读 Greg Lims 的关于 Node.js、express 和 mongodb 的书,当使用表单将资料发送到路由时,我被困在了这一点上,然后该路由将控制台输出 body.title 的形式。我得到状态 404 Not Found。推荐人 Policystrict-origin-when-cross-origin。我需要有关 CSP 和 CORS 的教育,但不知道从哪里开始?
我的 index.js 和 form.html ...
const express = require('express')
const bodyParser = require('body-parser');
const app = new express()
const cors = require('cors');
app.use(express.static('public'))
const path = require('path');
const { header } = require('express/lib/request');
app.use(express.static(__dirname '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cors({
origin: "*",
})
);
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.listen(4000,()=>{
console.log('App listening on port 4000')
})
app.get('/',(req,res)=>{
console.log('get root')
res.sendFile(path.resolve(__dirname,('pages/index.html')))
})
app.get('/about.html',(req,res)=>{
console.log('get about')
res.sendFile(path.resolve(__dirname,('pages/about.html')))
})
app.get('/post.html',(req,res)=>{
console.log('get post')
res.sendFile(path.resolve(__dirname,('pages/post.html')))
})
app.get('/store',(req,res)=>{
res.set("Content-Security-Policy", "default-src 'self', form-action 'self',script-src 'self'");
console.log('store post')
console.log(req)
console.log(req.body)
console.log(req.body.title)
res.redirect('/')
})
my form
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self', form-action 'self',script-src 'self'">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create</title>
</head>
<body>
<H1>Create Page</H1>
<form action="/store" method="POST">
<div >
<div >
<label>Title</label> <input type="text" placeholder="Title" id="title" name=”title” >
</div>
</div>
</div>
<br>
<div > <button type="submit" id="sendMessageButton">Send</button>
</div>
</form>
</div>
</div>
</div>
<meta http-equiv="Content-Security-Policy" content="default-src 'http://localhost'">
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'"> -->
<hr>
</body>
</html>
...
uj5u.com热心网友回复:
您的示例中没有 POST 端点,它们都是GET
. 据我所知,您<form />
真正想要的是 POST 到store
. 如果是这种情况,请更换此位
app.get('/store',(req,res)=>{
res.set("Content-Security-Policy", "default-src 'self', form-action 'self',script-src 'self'");
console.log('store post')
console.log(req)
console.log(req.body)
console.log(req.body.title)
res.redirect('/')
})
对于这一点。请注意,我只更改了 HTTP 动词。
app.post('/store',(req,res)=>{
res.set("Content-Security-Policy", "default-src 'self', form-action 'self',script-src 'self'");
console.log('store post')
console.log(req)
console.log(req.body)
console.log(req.body.title)
res.redirect('/')
})
请阅读Express 上基本路由的官方档案。这应该会给你一些见解。
0 评论