gpt4 book ai didi

通过node.js的ajax跨域发布

转载 作者:太空宇宙 更新时间:2023-11-04 02:38:30 24 4
gpt4 key购买 nike

我设置了一个 ajax post 到一个 php 文件,它使用 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);

}
});

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

最佳答案

您可以使用给定的 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();
}

关于通过node.js的ajax跨域发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com