404 / server Not Found - Nodejs Ajax

时间:2017-07-21 07:37:12

标签: javascript jquery node.js ajax

我正在尝试将数据从app.js发送到nodejs server.js,但AJAX提供错误POST http://localhost:9615/server 404 (Not Found)

当我在浏览器上打开http://localhost:9615/server时,它工作正常并显示所需的输出callback('{"msg": "OK"}')

这是 app.js 代码

我也试过网址:'服务器'和' / server'

       $.ajax({
            url: 'http://localhost:9615/server',
            // dataType: "jsonp",
            data: '{"idToken": '+idToken+'}',
            type: 'POST',
            jsonpCallback: 'callback', 
            success: function (data) {
                var ret = jQuery.parseJSON(data);
                console.log('Success: '+ret.msg);
            },
            error: function (xhr, status, error) {
                console.log('Error: ' + error.message);

            },
        });

这是 server.js 代码

app.get('/server', function(req,res, next){
    console.log('Request received: ');
    util.log(util.inspect(req)) 
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');
 });

浏览器屏幕截图:

enter image description here

控制台屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:2)

您正尝试在GET端点上发布内容。

更改为帖子

app.post('/server', function(req,res, next){
    console.log('Request received: ');
    util.log(util.inspect(req)) 
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');
 });

答案 1 :(得分:1)

因为当你这样做的时候 浏览器中的“http://localhost:9615/server”获取请求

&安培;您在代码中尝试的是发布请求。

根据您的使用情况更改任何一个。!

相关问题