【发布时间】:2020-11-25 16:26:50
【问题描述】:
我在 html 中有以下表单,我通过以下方式将其数据传递到 JavaScript:
<input type="text" class="form-control" id="input01" name="job_title" placeholder="Enter a job title (e.g. Engineering)">
<button class="btn btn-primary ml-auto" id="form_submit_button">Search</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script type="text/javascript" src="parser.js"></script>
(function($){
"use strict";
jQuery(document).ready(function($) {
var $this = $(window);
$("#form_submit_button").on("click", function () {
//GET VALUES FROM USER INPUT AND STORE IN VARIABLES
var job_title = $("#input01").val();
var jsonObjects = JSON.stringify({
job_title
});
console.log(jsonObjects);
//PASS DATA INTO NODE VIA HTTP POST REQUEST
const xhr = new XMLHttpRequest();
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.open(
"POST",
"http://localhost:80/test01",
{
job_title,
job_country,
job_contract,
job_education
}
);
xhr.send();
});
});
})();
当我点击按钮假设我在输入字段中添加了一些数据时,程序会将信息传递给 JavaScript,但由于以下错误,未触发 http 请求:
{"job_title":"database"}
Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
at HTMLButtonElement.<anonymous> (http://public-ip-address/test/parser.js:26:17)
at HTMLButtonElement.dispatch (http://public-ip-address/test/scripts/jquery/jquery.min.js:2:43090)
at HTMLButtonElement.v.handle (http://public-ip-address/test/scripts/jquery/jquery.min.js:2:41074)
当我在xhr.open(...) 下方添加以下xhr.setRequestHeader('Content-Type', 'application/json'); 时,会出现以下错误:
{"job_title":"database"}
Access to XMLHttpRequest at 'http://localhost/test01' from origin 'http://public-ip-address' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这里是节点:
const express = require('express');
const app = express();
app.get("/test01", (req, res) => {
res.send("hello world");
})
app.listen(80, ()=> {
console.log("\n > Server running on port: 80");
});
我的网站使用我的公共 IP 地址托管在 noip.com。但是我不能也不知道如何通过我的 URL 访问我的节点服务器。请注意,http://localhost:80/test01 将在浏览器上显示 hello world。
任何帮助将不胜感激,谢谢!
更新:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: '*',
optionsSuccessStatus: 200,
}));
app.get("/test01", (req, res) => {
res.send("hello world");
})
app.listen(80, ()=> {
console.log("\n > Server running on port: 80");
});
更新后浏览器出错
POST http://localhost/test01 404 (Not Found)
(anonymous) @ parser.js:39
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2
【问题讨论】:
-
看起来您所说的问题恰恰相反(从节点访问特定网站)。如果我错了,请纠正我
-
最后一个错误是来自您本地运行的网站副本还是您通过 noip 访问的那个?
-
所有进程都通过我在noip.com中的主机名访问过
-
...您的 XHR 代码在做什么,以及您从哪里得到 CORS 错误...?
标签: javascript html jquery node.js