1

I set up an ajax post to a php file, which uses htaccess CORS to answers with a simple html string. The twist is, the ajax post will work when i use a xmapp server instead of my node.js server. Also i tested it with 2 different target domains, both with the same htaccess an the same php file. With sending from xampp both work, with sending from node.js only one works.

Error: XMLHttpRequest: Only GET method is supported

Javascript ran in 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}]

Target php file:

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

1 Answers1

0

You can use given code for 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();
}
Ajeet Kumar
  • 156
  • 1
  • 10