当触发ajax请求时,我在控制台中收到以下错误消息:POST http://localhost:3000/speichern 500(内部服务器错误)
并在节点cmd中:ENOENT:没有这样的文件或目录,stat' pathtodir / speichern'
我在Javascript文件index.html中有这个Ajax请求:
$.ajax({
url:"http://localhost:3000/speichern",
method:"POST",
contentType:"application/json",
data:JSON.stringify({highscore:score,name:name}),
dataType:"JSON",
success:function(responseData){
console.log("Daten gespeichert");
}
})
和我的server.js中的代码
bp = require("body-parser");
express = require("express");
fs = require('fs');
serve = require("express-static");
app = express();
app.listen('3000',function(){
console.log('server started on 3000');
});
app.use(bp.json());
app.use(serve(__dirname+'/'));
app.use(function(request,response,next){
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Methods','POST,OPTIONS');
response.setHeader('Access-Control-Request-Headers','Content-Type');
response.setHeader('Access-Control-Allow-Headers',"Origin, X-Requested-
With, Content-Type, Accept");
next();
});
app.post('/speichern',function(request,response){
console.log('post speichern called');
var thejson = {
something:'test'
}
response.end(JSON.stringify(thejson));
});
答案 0 :(得分:1)
在配置路由之前,您已开始listen
到服务器。
移动以下行:
app.use(serve(__dirname+'/'));
app.listen('3000',function(){
console.log('server started on 3000');
});
到代码的末尾