【发布时间】: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&{%22user_name%22:%22rv%22,%22password%22:%22rv%22}&_=1455570384049在红毯上。
标签: javascript jquery ajax node.js express