首页 > 解决方案 > 如何从外部访问 localhost asp.net core web api

问题描述

我有反应本机应用程序。我想从 asp.net 核心 Web API 获取数据。我想从外部访问本地主机 asp.net 核心 Web API(从反应本机应用程序)

标签: reactjsapinativewep

解决方案


您可以使用许多第三方库进行 HTTP 请求,例如 axios,甚至在您想要访问核心 Web API 时获取 XMLHttpRequest。您可以使用以下方法,无论您的端点是什么。

 fetch('https://jsonplaceholder.typicode.com/posts/1', {
         method: 'GET'
      })
      .then((response) => response.json())
      .then((responseJson) => {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) => {
         console.error(error);
      }); 

使用 XMLHttpRequest

var xhr = new XMLHttpRequest()
    xhr.addEventListener('load', () => {
      console.log(xhr.responseText)
    })
    xhr.open('GET', 'https://dog.ceo/api/breeds/list/all')
    xhr.send()

使用 axios

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
  });

推荐阅读