POST AJAX调用无法使用Express JS

时间:2016-02-15 20:53:55

标签: javascript jquery ajax node.js express

  

这是我的NodeJs文件

var express = require('express'),
//http = require('http'),
app = express(),
bodyParser = require('body-parser');

app.use(bodyParser.json());         // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/',function(req,res,next){
var result = {};
res.writeHead(200,{"Content-type":"text/plain"});
result.status = true;
res.write(JSON.stringify(result));
res.end();
});

// Default/Fallthrough method for any route not handled when using http package.
app.use(function(req,res,next){
    res.sendStatus(404);
});

app.listen(1337,function(){
    console.log("Server started successfully at Port 1337!");
});
  

这是我在.html文件中的AJAX请求

<!DOCTYPE html>
<html>
<head>
    <title>tester.html</title>
</head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<h1 id="answer"></h1>

<script>

var ele = $("#answer");
//ele.append("Hello World!!!");

var datapassed = {user_name: "rv", password : "rv"};

$.ajax({
    url: 'http://localhost:1337',
    async: false,
    type: 'POST',
    dataType: 'jsonp',
    data : JSON.stringify(datapassed),
    contentType: "application/json",
    success: function(data) {
        alert(data);
        //  ele.append(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    }
});

</script>

</html>
  

我的基本目标是制作一个使用ExpressJS作为框架在NodeJS中构建的API的Web应用程序。 AJAX是我想到的第一件事,就是向API发出服务器端请求,以便在应用程序上显示实时数据。我尝试了一切,但似乎没有任何工作。 AJAX调用不会返回任何内容。控制台说

无法加载资源:服务器响应状态为404(未找到)

欢迎除AJAX以外的任何其他选择。

1 个答案:

答案 0 :(得分:0)

首先,如果你正在使用JSONP,那么使用HTTP POST方法是不可能的,因为JSONP的工作方式,你只能使用GET。 / p>

其次,您需要在Express路由(source)中选择加入JSONP支持,否则它将无法接受JSONP请求。所以改变你的路线(如果你想继续使用JSONP):

app.get('/',function(req,res,next){
  var result = {};
  result.status = true;
  res.jsonp(JSON.stringify(result));
});

如果您想使用常规JSON,请将其更改为

app.post('/',function(req,res,next){
  var result = {};
  result.status = true;
  res.json(JSON.stringify(result));
});

为了使用常规JSON请求,HTTP调用必须来自与API端点在同一主机和端口上的HTML页面。您可以通过使用express.static让快速服务器为您的HTML文件提供服务来实现这一目标,如下所示:

app.use(express.static(__dirname + '/client')); //serve all files in the 'client' folder