有一个django项目,apache2服务器,Ubuntu18.04系统,在js项目中有一个脚本,需要从该脚本向本地服务器上的一个php脚本发送POST请求。在 /etc/hosts 中将域 myserver.com 分配给 IP 127.0.0.1,在 Apache 中配置 /web 根文件夹。但是尝试向服务器发送请求会导致错误
POST http://myserver.com/script/ net::ERR_NAME_NOT_RESOLVED
如果你放的是localhost地址而不是域,那么就不会出现这个错误,但是会出现CORS错误:
POST http://localhost/script/ 404 (Not Found)
Access to XMLHttpRequest at 'http://localhost/script/' from origin 'http://site.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
但是在具有相同设置的 Windows 计算机上,一切正常。
脚本.js:
sendMail: function (formid) {
var formId = "#" + formid;
var fd = new FormData(document.querySelector(formId));
var url = 'http://myserver.com/script/';
$.ajax({
url: url,
type: "POST",
data: fd,
cache: true,
processData: false,
contentType: false,
beforeSend: function () {
...
索引.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>myserver</title>
</head>
<body>
<h2>myserver</h2>
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: *");
require_once 'script.php';
?>
</body>
</html>
最好的 url 是做“文件的相对链接”,然后将站点从一台服务器转移到另一台服务器时,什么都不会改变。
一切都异常平庸。客户端js自然敲的是客户端的本地主机,而不是站点,自然在那里什么也看不到。因此所有的错误。您必须首先将请求传输到站点,然后从站点传输到本地服务器。或者给服务器挂个白IP地址。