First of all, my file structure:
web
-public
--login.html (the login page is a static page)
-veiws
--index.jade
- routes
--index.js
-app.js
Front-end code
$("#login").click(function(){
var username=$('#un').val();
var pw=$("#pw").val();
var data = {"un":username,"pw":pw};
$.ajax({
type:"post",
url:"/login",
async:true,
success: function(data,status){
if(status == 'success'){
location.href = '../views/index.jade';
}
},
error: function(data,status){
if(status == 'error'){
alert("密码或者用户名错误");
}
});
})
What should I write in the url in $.ajax?
In addition, should my server code be written in app.js or index.js in the router folder? Or create a new js file and write the server code into it, and then write the relative directory of the js file in the URL (this seems to be the case with PHP).
There is also router.get('/', function(req, res, next){}) in index.js and var router = require('./routes/index) in
app.js ');app.use('/',router) What is the difference? Which one is the binding domain name? My understanding is that after the server is started, app.js is automatically run and then app.use is equivalent to pushing the functions into a stack and executing them sequentially. Then when index.js is executed, index.js renders the jade template in views according to the URL address, and every Refresh and re-render (it’s not clear whether app.js is re-executed without refreshing or index.js is re-executed).
You can try entering the following code in segmentFault’s console
Then you will get / the content of this html file.
Your question
Suppose you are listening on port 3000 and you have defined the /login route
Then the URL should be /login
The content behind app.use is called middleware
For example, I visit http://localhost:3000/api/login
It just so happens that I have a middleware that can match /api/login. Then express will hand over req res to this middleware for processing
URL can be relative or absolute. Starting from
http(s)://
, you can specify the URL on any domain name, but please pay attention to the issue of cross-domain access. Relative is the URL relative to the current page,/<path>
/
, relative to the root, which is the Domain (host domain name) where the current page is located../<path>
../
can be used together to represent the upper layers./
./
have the same effectWhat needs to be noted here is the identification of the current page path, because
folder/
in the URL can be abbreviated tofolder
, and whether or notfolder/
有可简写成folder
,而有没有/
represents a completely different location (in today’s world When routing is widely used, directories or pages are no longer distinguished by extensions), so it is generally recommended that the front end at least write a path relative to the root.You write '/' to represent the current port, and url is your path in nodejs