I am trying to load external data with fetch into a react-native mobile app. I have tried with different sources and mostly I get an error message saying the network can't be found.
For instance I have tried with the following two sources.
http://facebook.github.io/react-native/movies.json (does not work)
https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json (works)
componentDidMount(){
var REQUEST_URL = 'http://facebook.github.io/react-native/movies.json';
fetch(REQUEST_URL).then((response) => {
console.log(response);
if(response.ok) {
console.log('Response OK');
} else {
console.log('Network response was not ok.');
}
})
.catch((error) => {
console.log('There has been a problem with your fetch operation: ' + error);
})
.done();
}
I am testing in IOS simulator on my MacBook.
I also tried to get json data from my WordPress site, with the latest version of the WP REST API plugin installed. Also this returned a can't find network error.
I am really stuck on this one.
That’s caused by apple’s security rule, http protocol is restricted(you are sending a http request).
If you need communication in http protocol, there are two solutions(all related to info.plist):
1: Just like what the quick start project does, add the domain name of server:
2: Add a new rule: “Allow Arbitrary Loads”. don’t forget set the value to “YES”.
Related
I'm creating a React Application, and it is hosted on localhost:3000. I want to fetch data from a .NET Core Application hosted on localhost:5001. I'm using axios library to make http requests.
The function in which I make the request is:
async componentDidMount() {
const data = await axios.get("http://localhost:5001/api/gateways");
console.log(data);
}
The obtained Error is "Unhandled Rejection (Error): Network Error".
I tried to test the API with Postman and it works, as well as accessing it from the browser and it works too.
At the same time I tried to consume data from another API, this time hosted on an online server, and it worked perfectly, that means, the problem must be between two applications hosted on the localhost.
I fixed this issue by adding an Access-Control-Allow-Credentials header to HTTP responses in .NET CORE application. This header tells the browser that the server allows credentials for a cross-origin request.
Its necessary modify Configure method at Startup.cs fileadding the following code:
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
await next.Invoke();
});
And, it is also necessary modify ConfigureServices method with:
services.AddCors(c =>
{
c.AddDefaultPolicy(options => options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
I ran into a small problem while deploying a react app on GitHub pages. The app works perfectly fine on a live server. But, when I push the code on gitHub and test it. This error occurs:
Mixed Content: the page at '<domain>' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoing 'http://www.omdbapi.com/...' ...
I know it has something to do with the api I m using. It's omdb api and uses HTTP protocol for a get request. I tried changing the HTTP to https and though it works on the live server. It does not on the Github page, giving me the same error as before.
Code:
const apirul = 'http://www.omdbapi.com/?apikey=...';
// ...
Axios(apiurl + "&=s="+state.s)
.then(data => {
console.log(data);
let results = data.Search;
setState(prevState => {
return { ...prevState, results }
})
})
.catch(e => {
console.log(e)
})
// ...
Looking at the GitHub Pages and the source it's got, I suspect your push to GitHub failed as the code in the repo is still pointing to http://www.omdbapi.com/?apikey=ad5bdfd0 (and was last updated 17 hours ago). I took a screenshot to to confirm.
Changing it the URL to https:// should fix it, though you could use a protocol relative url (that is, //) if you had to. Really, you should be using https for everything now, even local development.
I use the first example here in order to get the geo coordinates based on an address:
https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html
My JavaScript coding looks almost the same as in the official documentation:
var platform = new H.service.Platform({
'apikey': 'HERE IS MY API KEY'
});
// Get an instance of the geocoding service:
var service = platform.getSearchService();
service.geocode({
q: 'Berlin'
}, (result) => {
result.items.forEach((item) => {
console.log("test");
});
}, alert);
However, when the geocode request is sent, I get the following error:
Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The API key is sent correctly, why do I still get the CORS error?
If I enter the request URL manually in the browser, I get a response and everything is fine.
Yes, the server will help with the issue. I'm here to suggest the alternative.
You can do the geocoding with the HERE Maps REST as well see docs — https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html.
Since not all the browsers historically support the CORS (learn more about the CORS — https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) there is an approach, called JSONP. See some JSONP explanation Here Maps related in the old docs https://developer.here.com/documentation/places/dev_guide/topics/request-cross-domain-js.html.
Eventually the https://www.npmjs.com/package/jsonp npm package could be a good follow up and we can get something like this after installing the package (npm install jsonp --save).
import jsonp from 'jsonp';
jsonp('https://geocode.search.hereapi.com/v1/geocode?q=5+Rue+Daunou%2C+75000+Paris%2C+France&apiKey=my-api-key',
null,
(err, data) => {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
This works great from my experience.
If you are testing this code by opening the file in the browser, you may get this error. I suggest using a local server for testing.
I am attempting to run a React/Rails Website locally for 2-3 users within a closed network. Currently, the users can reach the React portion (I have that set to port 80). The problem is, the API calls I have set to my Rails backend are all on localhost:3001 and the users have zero access to that database when I try to submit HTTP requests.
I know it's a CORS issue but I thought the code below would allow any domain to make the necessary request.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Server side work is not my forte, so I may be missing something glaring. Any idea how to open up that backend so the networked users can make API Calls on their end?
React is on this ip: http://192.168.2.70:80/
API calls on this port: 3001
Example API call from front end (works on host computer; not on other users):
getData = () => {
axios.get('http://localhost:3001/api/v1/pickup_deliveries')
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
The Problem
Unless I missed something, it looks like you're making a simple mistake that you're going to smack yourself for.
Typically, a CORS issue in a JavaScript application would yield a CORS/pre-flight request error error in your browser's JavaScript console.
The Misconception
The JavaScript that makes up a React application is downloaded by the client (i.e. your users). After that, the fetch call is executed on the client's computer. The fetch request doesn't originate from the server, but rather from the remote end.
It works on your computer because both React and the Rail API are hosted on your computer, so localhost:3001 resolves correctly. However, on your users computer, the React app attempts to find a service running on port 3001 on their computer.
Initial Solution
You need to tell React to reach out to the IP server that's hosting the API, like this:
getData = () => {
axios.get('http://192.168.2.70:3001/api/v1/pickup_deliveries')
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
Long Term Solution (for deployment)
In the future, look into dotenv, which will allow you to set React environment variables. You could have a .env.local file, and a .env.production file.
In the local file, you could put:
REACT_APP_BACKEND_SERVER=http://localhost:3001
and in the production on you could put:
REACT_APP_URL=http:/<server_ip>:3001
Then, in your program, do something like:
getData = () => {
axios.get(process.env.REACT_APP_SERVER_URL + "/api/v1/pickup_deliveries")
.then((response) => {
this.setState({
apiData: response.data})
})
.catch((error)=>{console.log(error);});
}
This will automatically resolve to localhost when serving React using npm run start and then resolve to <server_ip> when you are serving the static files generated by npm run build.
Feel free to comment on this answer. I would be happy to answer any other questions you have. Welcome to React!
I've created an Ionic app which calls an API to post the user's current location.
The request works as follows:
POST: http://mywebsite.com/api/Patients/AddLocation/17
with body:
{
"Latitude": 51.3753786,
"Longitude": -0.0833691
}
However, the following code in my Ionic app does work:
$http.post('http://mywebsite.com/api/Patients/AddLocation/' + $scope.id, data)
.success(function () {
console.log('Updated location');
})
.error(function (error) {
console.log('Error updating location');
console.log("Error: " + error);
});
In which 'data' is the same as the body above.
Any ideas why this isn't working?
UPDATE:
Here's a couple of screenshots of the network request:
Network request available at imgur RWNDF.png
Postman request
It happens if you have not enabled cors in your server.
enable cors in you server.
even if you dont enable cors,
get method will work peerfectly if you have enabled cors using any extension in chrome.
It's because of CORS. Enable cros from the server end and the a header will be set in HTTP Access-Control-Allow-Origin: * .
If your server app is an expressjs app, use below code to enable CORS
var cors = require('cors');
.....
app.use(cors());
Else use chrome extension Allow Cross Origin Request
This should solve the problem
After comparing this to a sister app which uses the same API and works, the only difference I could see was that a few of the plugins were different.
To remedy this I deleted the plugins folder and the platforms folder, re-added android and just the plugins I need, it now works. I guess it's maybe some bug I created by using the wrong mixture of plugins.
A very unsatisfying answer, but all requests work now!