var path = require('path');
var express = require('express');
var app = express();
// 定義靜態檔案目錄
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, function () {
console.log('app listening on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax - sample</title>
</head>
<body>
<input type="text" name="username" />
<button id="btn">Get user from Github</button>
<p>
<p id="avatar"></p>
<p id="username"></p>
<p id="blog"></p>
</p>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(function () {
$('#btn').on('click', function (e) {
var username = $('input[name=username]').val();
$.get('https://api.github.com/users/' + username, function (result) {
console.log('ajax completed', result);
var avatar = new Image(80, 80);
avatar.src = result.avatar_url;
$('#avatar').append(avatar);
$('#username').text(result.login);
var a = document.createElement('a');
a.innerHTML = "BLOG"
a.setAttribute('href', 'http://www.google.com');
$('#blog').append(a);
})
});
});
</script>
</body>
</html>
可否提供更詳細的訊息呢?
這邊我用
express@4.13.4
實作一個簡單的 ajax get 是正常的。你設定路由,用app.get(routerurl,function(req,res){
res.sendfile(你的檔案)
})
一般public都放的是樣式和瀏覽器的js。
然後你ajax上傳路徑也設定成這個路由。用app.post.