我正试图从客户端发送一个更改的变量到服务器,但我不能弄清楚。我想要实现的是我可以在main. js中使用它。
<script>
document.getElementById("char2btn").addEventListener("click", change)
function change() {
charOneInView = "Yes"
const data = {charOneInView}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('/welcome2', options)
}
</script>
Index.js:
var charoptioneOne = "No"
router.post('/welcome2', ensureAuthenticated, function(req, res){
console.log(req.body)
res.redirect('/main');
})
router.get('/main', ensureAuthenticated, (req, res) =>
res.render('main', {
user: req.user,
charOneInView: charoptioneOne,
charTwoInView: charoptioneTwo
})
)
对我来说,它看起来仍然是一个对象,而不是一个改变的变量,我如何解决这个问题?
在后端使用body-parser模块
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
设置请求头:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}