如何从localhost向api发出获取请求?

如何从localhost向api发出获取请求?,api,http,request,Api,Http,Request,我正在制作一个条形码扫描仪应用程序。当我发出一个获取请求时,localhost被连接到api url的前面,并返回一个404。当我发出一个获取请求时,它只包含我试图获取到的api url,我如何修复这个问题 export const getUpc = (text) => { return dispatch => { let url = "api.upcitemdb.com/prod/trial/lookup" let req = new Request(url , {

我正在制作一个条形码扫描仪应用程序。当我发出一个获取请求时,localhost被连接到api url的前面,并返回一个404。当我发出一个获取请求时,它只包含我试图获取到的api url,我如何修复这个问题

export const getUpc = (text) => {
  return dispatch => {
  let url = "api.upcitemdb.com/prod/trial/lookup"

  let req = new Request(url , {
    hostname: 'api.upcitemdb.com',

    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': 'http://127.0.0.1:3000'
    },
    mode: 'no-cors'
  })

  let product = null
  fetch(req)
  .catch(err => console.log('error', err))
  .then(res => {
    console.log(res.status)
    if(res.status !== 200){
      return {
        resStatus: res.status
      }
    } else if(res.status === 200) {
      console.log(res)
      return res.json()

    }
  })
  .then(parsedRes => {
    if(parsedRes.resStatus !== 200){
      parsedRes.resStatus === 0 ? dispatch(invalidBarcode('noAPI')) : dispatch(invalidBarcode('invalid'))
    } else {
      product = parsedRes
      console.log(product)
      dispatch(productDetected(product))
    }
  })
  }
}
我在控制台中遇到此错误:
获取404(未找到)

这是因为
url
中缺少协议信息。要使其工作,变量
url
应为
http://api.upcitemdb.com/...
https://api.upcitemdb.com/...
(取决于api.upcitemdb.com服务器支持的协议)

在中,
请求
的构造函数定义为:

请求(输入,初始化)构造函数必须运行以下步骤:

  • 如果输入是字符串,则:

  • 让parsedURL成为使用baseURL解析输入的结果

  • 也就是说,如果缺少
    http://
    https://
    ,它会将当前服务器作为“baseURL”(
    http://127.0.0.1:3000/
    ),并将
    api.upcitemdb.com
    作为URL路径的一部分(而不是主机名)。

    URL中缺少协议。请使用
    http://api.upcitemdb.com/...
    https://api.upcitemdb.com/...
    这很有效。我再也不会忘记这一点了。谢谢,不客气。我添加了一个答案来描述这个问题的根本原因和解决方案。最后一段为我解决了这个问题。OpenWeatherAPI提供的url没有http,当我将其添加到fetch方法时,localhost url会自动添加到api url之前,这给了我一个错误。谢谢这一点。不客气,盖尔。