React Axios Appends Window Origin To Provided Url (json-server) - reactjs

I have a weird behaviour while integrating a json-server api with axios.
I use json-server to serve a db.json file
json-server --watch db.json --port 4000
and in my react application I use axios to call "http://localhost:4000/tasks"
Testing it on postman, the API returns results and it is working fine.
but using the code snippet below (axios) it concatenates both domains of the react app and the api Url to the request.
try {
return axios({
method: 'GET',
url: `http://localhost:4000/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
I check in the browser network and I the request Url like that
Request URL: http://localhost:3000/http//localhost:4000/tasks
and therefore throws a not found - 404 exception
Any idea why is this happening?
The weird thing is that When I use another API like star wars api "https://swapi.co/api/people/1", It works like a charm.
Thanks in advance...

I've fixed this problem by using environment variables.
I just created a ".env.development" file and added "REACT_APP_API_BASEURL = 'http://localhost:4000'".
And then I used it as follows:
try {
return axios({
method: 'GET',
url: `${process.env.REACT_APP_API_BASEURL}/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
and it worked perfectly.

Just faced this issue, it's because the url used in axios is wrong. In this case, the url in the original question is
http://localhost:3000/http//localhost:4000/tasks
Notice http//localhost:4000/tasks this is missing a colon after http. Fixing the url will fix this issue in case someone else is facing this again

Related

Expressjs Server cannot handle Requests from the Outside

I have a ExpressJs Server with React Components. And the Server should handle Requests from Outside and one request should play a Song from the Spotify API when not currently playing.
app.post("/play", (req, res) => {
try {
// requesting to play uses query params
id = req.query.id;
currPlayingID = 0;
// get the currently playing song from the SPotify API
axios({
url: "https://api.spotify.com/v1/me/player/currently-playing",
method: "get",
headers: {
authorization: `Bearer ${access_token}`,
},
})
// set the currently Playing ID or to zero if nothing is playing
.then((response) => {
if (response.data !== null) {
currPlayingID = response.data.id;
} else {
currPlayingID = 0;
}
});
// only play the song if its not currently playing
if (id !== currPlayingID) {
// making a axios request to the Spotify API to play the Song with the ID
axios({
url: "https://api.spotify.com/v1/me/player/play/",
method: "put",
headers: {
authorization: `Bearer ${access_token}`,
},
data: {
uris: [`spotify:track:${id}`],
},
});
res.status(204);
}
} catch (error) {
res
.status(404)
.json({ message: "Couldn't get Info from Spotify API", error: error });
}
});
The Problem:
The Code works when I start the server on the device itself (so a local server on my Desktop PC), but when I start the Server on my RaspberryPI i cannot handle Requests to this endpoint /play. Yeah I updated all the IP Adresses, everywhere.
But the moer ointeresting part is using the React Client I get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Requesting with POSTMAN I get the following:
Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource
And from a request using a python script I get on the server side:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 400".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I have no clue how to fix each error and if it is one fix. Basically I found out it is a Problem with rejeccting requests from outside localhost, because with cURL on my ssh terminal it works.
I'm learning express, so I m not an expert, but I'm looking at your errors. I will suggest you try asyncHandler module. It handles asynchronous requests and exceptions.
I faced a similar issue because while I'm sending the API request via
Axios, my token is null/empty/wrong, so make sure your token is correct
this is my request format
axios({
method:"POST",
url:"https://graph.facebook.com/v13.0/"+phon_no_id+"/message?access_token="+token,
data:{
messaging_product:"whatsapp",
to:from,
text:{
body:"Hi.. I'm Prasath"
}
},
headers:{
"Content-Type":"application/json"
}
});

Getting "TypeError: Failed to fetch" with some url

I'm facing "TypeError: Failed to fetch" errors in my React App.
Depending on the url of the query I run I sometimes encounter the error, although the query does return a valid result when I test it in my browser.
Here are two examples with two sample URL:
(function(){
var GetRequestResult = function (url) {
return fetch(url, {
headers: { 'Access-Control-Allow-Origin': '*'}})
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.log(error))
};
this.GetRequestResult = GetRequestResult;
})(this);
console.log(GetRequestResult('https://jsonplaceholder.typicode.com/comments?postId=1')); // Works
console.log(GetRequestResult('http://api.plos.org/search?q=title:DNA')); // Returns 'TypeError: Failed to fetch'
So I have two questions:
Why the first one works and not the second ?
My final need is to retrieve a response from Google's Recaptcha API (https://developers.google.com/recaptcha/docs/verify) using the URL: https://www.google.com/recaptcha/api/siteverify . I am encountering the error on this url also.
I guess it's related to CORS (I tried to modify the Headers of my requests, to define https://www.google.com as a proxy, to use different methods to execute the requests ...) but without success. Any idea to solve this problem ?
The problem is solved.
I was trying to call the Google Recaptcha API (https://www.google.com/recaptcha/api/siteverify) from my frontend.
Due to Google's CORS policy this only seems possible from the backend side.
async function getRequest() {
fetch('https://api.plos.org/search?q=title:DNA')
.then( res => res.json())
.then( data => console.log(data.response.docs))
.catch( e => console.log(e))
}
The following code is working in nodejs

Axios in React app. Posting image with form data sends request with empty body

I'm trying to send image file to my backend API. Last works fine with Postman. The problem is not with image, I'm not able to send any request with axios and form data, no meter I append image or not.
Everything works fine with fetch. It took time to understand, that fetch does not need any content type, and last generates automatically as multipart/form-data with right boundary.
As written axios should do same as fetch, but it does not generate or change its content-type. Passing header 'content-type' : 'multipart/form-data does not do the trick of course. When I do not set content type it just use application/json. I was not able to find anything like that in documentation. Everywhere its says, that axios should create content type header automatically.
My axios version is 0.18.0.
Here is code, it can't be more simple =)
axios
.post(url, payload)
#######UPDATE#######
It turned out the problem was with axios interceptor. If you don't use interceptors you won't get this problem. So when I created new instance and deleted all headers no interceptors where called that's why my code worked. But let me bring more details to help others avoid this pain. Interceptor has transformRequest function where this part of code exists
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
where setContentTypeIfUnset function is
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
So if your object has undefined headers you will also pass this situation. But in my case even after deleting all headers I must pass some header to my application. And on setting it interceptor calls that transfromRequest function which adds that header to my formdata request.
I hope in future releases axios will fix this issue.
#######OLD ANSWER#######
As I guessed, somehow axios in my project set its default value for header content type and even setting it as 'content-type' : undefined did not overwrite that value.
Here is solution
let axiosInstance = axios.create();
delete axiosInstance.defaults.headers;
Then use that instance.
Spent whole day to find this solution.
const formData = new FormData();
formData.append('image', image); // your image file
formData.append('description','this is optional description');
Axios.post(`your url`, {body:formData}, {
headers: {
'content-type': 'multipart/form-data'
}
})
Can you please try this code once ?
You can try like this:
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

Can't access CakePHP API endpoint via ReactJS. Only through the browser

I am trying to build a REST API for my server via CakePHP. I thought I had it working as I can receive the JSON responses via the web browser however when trying to access the same route via ReactJS, the Controllers Action is not actually firing.
Reading the CakePHP docs I really should only have to implement these lines of code to get the API working (According to the docs) and I did:
/config/routes.php
Router::scope('/', function($routes) {
$routes->setExtensions(['json']);
$routes->resources('Users');
});
Here is the API Endpoint I want to hit:
`public function signUp() {
$file = fopen("error_log.txt", "w");
$txt = "firing endpoint";
$fwrite($file, $txt);
$fclose($file);
$response = $this->response;
$responseText = [
"status" => "200",
"message" => "User added successfully"
];
$response = $response->withType("application/json")
->withStringBody(json_encode($responseText));
return $response;
}`
Here I am successfully hitting that endpoint via the browser. My log message also appears in the error_log.txt file
Here is where I'm making a request via ReactJS:
handleRequest = () => {
console.log('making request');
axios({
method: 'get',
url: 'https://157.230.176.243/users/register.json',
data: {
email: this.state.email,
password: this.state.password
}
})
.then(function(response) {
console.log('got response');
console.log(response);
})
.catch(function(error) {
console.log('got error');
console.log(error);
})
.then(function(data) {
console.log('always executed');
console.log(data);
});
}
When I make this request via ReactJS I get a XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"
Also when making this request via ReactJS my log message does not get written to error_log.txt
Ok I finally figured out what was wrong. I have my React Development server running on
157.230.176.243:3001
and my CakePHP API served on that same server,
157.230.176.243
React didn't like it that I was passing the full URL of the API to the fetch()
call. I switched my React code to
url: "/users/register.json"
and it works fine.

Requests API in React-boilerplate

I am using the boilerplate on https://github.com/react-boilerplate/react-boilerplate . The problem is that when I'm hitting API's It's returning error 404. I'm not able to get from where it is setting up the host (which is always going localhost).
no CORS error is also coming up on browser.
Prior to this I was working on create-react-app, there I simple put a "proxy" property in package.json and everything worked fine.
Today I set up this boilerplate for the first time and I would say it's a lil confusing _:)
You can specify API base url like this:
const API = process.env.NODE_ENV !== 'production' ? 'http://google.com' : 'http://localhost:5000'
So in development it will always point to localhost and in production it will point to other your prod server.
For people still searching,
all you need is to create something like this in server/index.js
app.get('/api/user', (req, res, next) => {
let parsedBody = JSON.parse(req.body)
res.send({ express: 'Hello From Express.' });
});
on client side request to /api/user
axios.get(`/api/user`)
.then(function (response) {
console.log("/api/user response", response);
})
.catch(function (error) {
console.log(error);
});
cheers

Resources