【问题标题】:POST AJAX call not working with Express JSPOST AJAX 调用不适用于 Express JS
【发布时间】:2016-05-26 22:11:21
【问题描述】:

这是我的 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>

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

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

欢迎使用 AJAX 以外的任何替代方案。

【问题讨论】:

  • 你为什么使用dataType: 'jsonp'?你觉得那条线有什么作用?如果删除该行会发生什么?
  • 使用http://localhost:1337/ 解决了您的问题吗? (注意末尾的 /)
  • 如果我删除dataType: 'jsonp' ,我得到的结果是:XMLHttpRequest 无法加载localhost:1337。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。响应的 HTTP 状态代码为 404。
  • 为什么要指定 JSONP? JSONP 请求不能通过 POST 使用(它们必须是 GET,因此不能包含有意义的正文数据),必须是异步的,并且必须从服务器接收可执行脚本作为响应。没有一个与您在这里所做的相匹配。您是否指定 JSONP 以尝试允许跨域访问?在这种情况下,只需enable CORS
  • 最后加/没关系。不管添加或不添加/,控制台都会说:GET http://localhost:1337/?callback=jQuery111203430932753253728_1455570384048&amp;{%22user_name%22:%22rv%22,%22password%22:%22rv%22}&amp;_=1455570384049 在红毯上。

标签: javascript jquery ajax node.js express


【解决方案1】:

首先,如果您使用 JSONP,则无法使用 HTTP POST 方法,您只能使用 GET,因为 JSONP 的工作方式。

其次,您需要在 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 让 express 服务器为您的 HTML 文件提供服务来完成此操作,如下所示:

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

【讨论】:

  • 非常感谢 leroydev。顺便说一句,然后我使用 express JS 呈现了 ajax 页面。由于当时的请求在同一主机、同一端口和同一协议上,因此我不需要 jsonp。
猜你喜欢
  • 2016-06-07
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
相关资源
最近更新 更多