[英]React-native get error "Network request failed"
I'm new to the react native, and I'm trying to get data from API, but I got tired and could not find a solution.我是 react native 的新手,我正在尝试从 API 获取数据,但我累了,找不到解决方案。
I'm used:我习惯了:
- my react App - 我的反应应用
import { StatusBar } from "expo-status-bar";
import { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import Home from "./screens/Home";
export default function App() {
const [weather, setWeather] = useState("Loading..");
const getWeather = async () => {
var res = await fetch("https://192.168.1.205:5001/WeatherForecast", {
method: "GET",
})
.then((response) => response.json())
.then((responseJson) => {
alert("Succ");
// Handle response here
})
.catch((error) => {
console.error(error);
alert(error);
});
};
// return <Home />
getWeather();
return (
<View>
<Text></Text>
<Text style={{ paddingTop: 50, marginLeft: 30 }}>{weather}</Text>
</View>
);
}
- Controller - Controller
using Microsoft.AspNetCore.Mvc;
namespace RestaurantAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
- Prgoram.cs - 程序.cs
var builder = WebApplication.CreateBuilder(args);
var CorsPolicy = "_myAllowSpecificOrigins";
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicy,
b =>
{
b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
builder.WebHost.UseKestrel();
builder.WebHost.UseUrls("http://localhost:5001", "https://192.168.1.205:5001");
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection(); by waleed
app.UseCors(CorsPolicy);
app.UseAuthorization();
app.MapControllers();
app.Run();
- Postman Request - Postman 请求
when call this url in postman it get data当在 postman 中调用此 url 时,它会获取数据
when call api from ReactNative in visual code get this error:" Network request failed "当在可视代码中从 ReactNative 调用 api 时收到此错误:“网络请求失败”
Note:笔记:
but get same error, Please can any one help me.但得到同样的错误,请任何人帮助我。
thanks for all谢谢大家
Fetch fails on Android with that error if you don't set a Content-type header.如果您未设置 Content-type 标头,则在 Android 上获取失败并显示该错误。 Try adding one to your fetch request.尝试在您的 fetch 请求中添加一个。
headers: {
'Content-type': 'application/json'
}
Run your backend app using your Computer IP address eg on django its Python manage.py runserver 191.223.233.222:8000
then use "http://191.223.233.222:8000" on your react native domain. Run your backend app using your Computer IP address eg on django its Python manage.py runserver 191.223.233.222:8000
then use "http://191.223.233.222:8000" on your react native domain.
also on your app.json file under iOS add "ios": { "supportsTablet": true, "infoPlist": { "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true } } },
to give your permissions to allow http requests also on your app.json file under iOS add "ios": { "supportsTablet": true, "infoPlist": { "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true } } },
to give your permissions to allow http requests
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.