API获取请求未在javascript中解析



屏幕截图

我想知道是不是因为它试图访问两个IP?如果这是一个noob问题,很抱歉,但当我点击我的API时,我内置了poster,或者即使我只是将get请求url放入任何浏览器,它也会返回JSON数据。有点纠结于为什么它不会为我解决。

const app = document.getElementById('root')
const logo = document.createElement('img')
logo.src = 'logo.png'
const container = document.createElement('div')
container.setAttribute('class', 'container')
app.appendChild(logo)
app.appendChild(container)
var request = new XMLHttpRequest()
request.open('GET', '18.220.177.84:8080/election_results?state=Ohio&year=2016&county=Cuyahoga', true)
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach((election_results) => {
const card = document.createElement('div')
card.setAttribute('class', 'card')
const h1 = document.createElement('h1')
h1.textContent = election_results.county
const p = document.createElement('p')
election_results.candidate = election_results.candidate.substring(0, 300)
p.textContent = `${election_results.candidate}...`
container.appendChild(card)
card.appendChild(h1)
card.appendChild(p)
})
} else {
const errorMessage = document.createElement('marquee')
errorMessage.textContent = `Gah, it's not working!`
app.appendChild(errorMessage)
}
}
request.send()

是因为我使用的是xmlhttp请求吗?

您显然在Postman GET调用中混合了两个独立的IP地址。

第一个只是本地主机(127.0.0.1:5500(,第二个是您试图访问的实际服务器(18.220.177.84:8080(

您的GET调用应该只命中(18.220.177.84:8080((删除第一部分,本地主机(

URL解析器认为18.220.177.84:8080是URL的路径的一部分。用//(以及可选的类似https方案来更改协议(对其进行预处理,以使解析器知道这是URL的authority(在这种情况下,host+port(。

所以问题出在代码中,您在没有提及协议的情况下向URL发出get请求。使用HTTP或HTTPS,以URL之前需要的为准。因此URL将是,

https://18.220.177.84:8080/election_results?state=Ohio&year=2016&county=Cuyahoga

希望这能解决你的问题。

现在来谈谈关于CORS错误的第二个问题。基本上,CORS或跨来源资源共享是一种标准,允许服务器过滤特定的跨来源请求,同时拒绝其他请求。在您的情况下,您的请求会被服务器阻止或拒绝。因此,为了解决这个问题,

  1. 如果您有权访问服务器,请允许您的来源进行来自您的来源的跨来源请求。您可以通过设置Access-Control-Allow-Origin: <Your origin>来执行此操作。例如,Access-Control-Allow-Origin: http://localhost:3000。您可以通过指定Access-Control-Allow-Origin: *,不过我强烈建议你不要这么做。

  2. 您可以使用代理服务器处理请求。通过此链接了解更多信息。

  3. 使用类似Moesif Origin&CORS Changer,尽管它只适用于您的浏览器,并且只能用于开发。(不推荐(

最新更新