52,797
社区成员
发帖
与我相关
我的任务
分享
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
response here: <p id="lblResponse">fill me in</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:1337/',
// dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});
</script>
</body>
</html>
var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
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\"}\')');
}).listen(1337,'127.0.0.1');
console.log('Server running on port http://127.0.0.1:1337/');
var express = require('express');
var app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.get('/auth/:id/:password', function(req, res) {
res.send({id:req.params.id, name: req.params.password});
});
app.listen(3000);
console.log('Listening on port 3000...');
在跨域状态下,jquery会转换为get请求,解决了跨域问题,就不会自动转换了.2 Apr 12:30:33 - Request recieved:
method: GET
url: /?hello=nihao&callback=callback&{%22data%22:%20%22TEST%22,%22nani%22:%20%22
no%20way%22}&_=1364931033077
{ hello: 'nihao',
callback: 'callback',
'{"data": "TEST","nani": "no way"}': '',
_: '1364931033077' }
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:1337/',
dataType: "jsonp",////////
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});