好的,我是 Express 新手。我正在搞乱 session 和 ajax 调用,但我遇到的问题是,每当我运行我的应用程序时,我的 jquery 由于某种原因无法工作。这是我的代码:
app.js
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var session = require('express-session')
var app = express();
app.use(express.static("public")); // I understand this is the directory where I would need to put all my static files: css, js, images, etc.
app.set("view engine", "jade");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Set secre pass for the session
app.use(session({secret:'password'}));
app.get("/",function(req, res){
if(req.session.userName){
res.render("admin", {session_name: req.session.userName});
}else{
res.render("home");
}
});
app.post("/example-ajax", function(req, res){
res.send(req.body.email); // return the email that was sent by the client
});
app.post("/log-in", function(req, res){
req.session.userName = req.body.name;
res.redirect("/");
});
app.get("/log-out", function(req, res){
req.session.destroy();
res.redirect("/");
});
app.listen(8080);
admin.jade
extends layout_head.jade
block content
div(class="container")
div(class="row")
div(class="col-lg-6 col-lg-offset-3")
h1 Logged In!!
h3 Logged in as: #[b #{session_name}]
a(href="/log-out") Log Out
br
div(class="btn btn-info testAjax") Test Ajax
script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js")
script(href="/css/bootstrap/js/bootstrap.min.js")
script(href="/js/main.js")
main.js
$(document).ready(function(){
alert("Loaded");
$(".testAjax").on("click", function(){
alert("test");
$.ajax({
type: 'POST',
url: '/example-ajax',
data: {
email: "admin@yahoo.com"
},
success: function(data){
// data = the email being returned from the server
console.log("Your email is: " + data);
}
});
});
});
就像我说的,每当我的页面加载或单击 testAjax 按钮时,jquery 都不会运行。当我检查控制台时,它没有给我任何错误,所以我不知道是什么导致了问题。
我的第二个问题是:这是在 Express 中进行 ajax 调用的正确方法吗?
非常感谢任何帮助。谢谢。
最佳答案
我只需要将脚本标签中的 href 更改为 src 即可。
关于javascript - jQuery 无法在 Express JS 中工作 - NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39194053/