ajax跨域发布通过node.js

时间:2013-10-27 19:38:27

标签: ajax node.js .htaccess cross-domain cors

我在一个php文件中设置了一个ajax帖子,它使用htaccess CORS来回答一个简单的html字符串。扭曲是,当我使用xmapp服务器而不是我的node.js服务器时,ajax post会起作用。此外,我测试了2个不同的目标域,两者都使用相同的htaccess和相同的php文件。从xampp发送两个工作,从node.js发送只有一个工作。

错误: XMLHttpRequest:仅支持GET方法

Javascript在node.js中运行:

$.ajax({
            type: 'POST',
            url: Customer[i]['phplink'],
            crossDomain: true,
            async: true,
            data: {
                status: 'hello',
                cachingtrap: (Math.random())
                },
            timeout: 4000,
            dataType : 'html',
            success: function(responseData, textStatus, jqXHR) {
                console.log('online:'+Customer[i]['name']);
            },
            error: function (responseData, textStatus, errorThrown) {
                console.log(errorThrown+ +textStatus+" "+responseData);

            }
        });

htaccess的:

# with AJAX withCredentials=false (cookies NOT sent)
Header always set Access-Control-Allow-Origin "*"                   
Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH, DELETE" 
Header always set Access-Control-Allow-Headers "X-Accept-Charset,X-Accept,Content-Type"
RewriteEngine On                  
RewriteCond %{REQUEST_METHOD} OPTIONS 
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]
# with AJAX withCredentials=true (cookies sent, SSL allowed...)
SetEnvIfNoCase ORIGIN (.*) ORIGIN=$1
Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH, DELETE" 
Header always set Access-Control-Allow-Origin "%{ORIGIN}e"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Headers "X-Accept-Charset,X-Accept,Content-Type"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]

目标php文件:

<?php
header("Access-Control-Allow-Origin: *");
if (isset($_POST['status'])) {
    echo round(microtime(true) * 1000);
} else {
    echo "Hello World";
}
?>

1 个答案:

答案 0 :(得分:0)

您可以使用nodejs express(more example click here)的给定代码:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}