1

我为一个 php 文件设置了一个 ajax 帖子,该文件使用 htaccess CORS 来回答一个简单的 html 字符串。扭曲的是,当我使用 xmapp 服务器而不是我的 node.js 服务器时,ajax 帖子将起作用。我还用 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);

            }
        });

访问:

# 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";
}
?>
4

1 回答 1

0

您可以为 nodejs express 使用给定的代码(更多示例单击此处):

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();
}
于 2018-04-17T09:53:50.603 回答