首页 > 解决方案 > express app ENOENT: no such file or directory ajax call 500 internal server error

问题描述

触发 ajax 请求时,我在控制台中收到以下错误消息:POST http://localhost:3000/speichern 500 (Internal Server Error)

并在节点 cmd: ENOENT: no such file or directory , 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));
});

标签: javascriptnode.jsexpress

解决方案


You are starting to listen to your server before you have configured your routes.

Move these lines:

app.use(serve(__dirname+'/'));
app.listen('3000',function(){
    console.log('server started on 3000');
});

to the end of your code


推荐阅读