Express '/' GET request fails, but '/' post, put, delete succeed - reactjs

I can't figure out what I'm doing wrong here so eyeballs or an idea on how to fix it would be appreciated
Express (4.17.1) + React (17.0.2)
This works fine:
router.get('/test', postListView)
router.post('/', postCreateView)
but this fails:
router.get('/', postListView)
Controllers:
const postListView = async (req, res) => {
// No output from req.method when route is to '/'
console.log(req.method)
res.json({message: 'List View'})
}
const postCreateView = async (req, res) => {
console.log(req.method)
res.json({message: 'Create View'})
}
My POST request React call (works fine):
fetch(`/`,{
method:'POST',
headers:{
'Content-type':'application/json'
},
body: JSON.stringify({title:text.current.value})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
GET request that fails:
fetch(`/`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
Error from GET request:
Unexpected token < in JSON at position 0
I can open the GET request in the browser by going to express directly (localhost:5000).
React is going through a "proxy":"http://127.0.0.1:5000"
I think I'm missing something fundamental with GET requests here but I can't see it so any help or docs would be appreciated.
Thank you,

Since you're using /test as resource path for GET route. Better you use the same route to make the GET request from your react application.
fetch(`/test`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
For / path, you need to specify which method you're using since you're using same path for both GET and POST request methods.
fetch(`/`, { method:'GET' })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

Related

Parsing fetched XML with react-xml-parser

I am first fetching xml data from an external api in my backend and then trying to send that to the frontend.
Backend (server):
app.get("/api", (req, res) => {
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://link',
'headers': {
}
};
request(options, function (error, response) {
console.log("TEST1")
console.log(response.body)
if (error){
console.log("TEST2")
res.status(404).write("NO LUCK");
}
console.log("TEST3")
res.status(200).write(response.body);
});
});
The xml appears in my terminal correctly. TEST1 and TEST2 do too.
Frontend (client):
import XMLParser from 'react-xml-parser';
useEffect(() => {
fetch("/api")
.then(res => res.text())
.then(data => {
var xml = new XMLParser().parseFromString(data);
console.log(xml)
})
.catch(err => console.log(err));
}, []);
Nothing appears on the console. I got the frontend code from this stack overflow post.
fetch("/api")
.then((res) => res.body)
.then((data) => console.log(data));
If I log the response body like this I get a ReadableStream object. This is the only functionality I've been implementing so far so nothing should be interfering with it. When I try different approaches I keep needing to restart React or it will load endlessly when I refresh.
When I open http://localhost:3001/api I can see the xml data I'm trying to transfer.
Still not sure why it didn't work before but it works with this.
Frontend (client):
import axios from "axios";
axios.get('/api')
.then(xml => {
console.log(xml.data);
})
Backend (server):
app.get('/api', (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'http://link',
headers: {'Content-Type': 'application/xml'}
};
axios(config)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
console.log(error);
})
})

ReactJS: post request with data through fetch

In my app component, I have state features that contains an array(1500) of arrays(9). I want to send the state (or large array) to my backend so I can run my model and return labels with the following function:
const getLabels = (model) => {
fetch('/spotify/get-labels', {headers: {
'model': model,
'features': features
}})
.then(response => response.json())
.then(data => setLabels(data))
}
However, the response has status 431. This was kinda expected, but I'm not sure how to transmit the data to my backend efficiently. Maybe convert it to json and then put in the headers of my request?
You can try something like this with fetch:
fetch('/spotify/get-labels', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ model, features }),
})
.then((response) => response.json())
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
or with axios
axios
.post('/spotify/get-labels', { model, features })
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
As far as I'm understanding your concern, I guess passing the 'model': model,'features': features in body should work.
Or using Axios, you can make the request. It exactly like Axios but far better
axios({
url: '/spotify/get-labels',
method: "post",
data: {
'model': model,
'features': features
},
})
.then((response) => response.json())
.then(data => setLabels(data))
.catch((error) => {
console.log("error : ", JSON.parse(error));
});

Axios not working properly when using window.location.href to redirect page in react

I'm using axios to send requests to my server. Now I wanted to apply redirects in my frontend(React) using the window.location.href property. But the axios request is not being sent. I also tried to carry out an axios request and reload the page and it doesn't work even then.
axios.post("/api/orders",params)
.then(res => {
console.log("Order Placed");
axios.delete("/api/cart/"+user_id)
.then(res => {
console.log("Cart Deleted");
})
.then(res => {
window.location.href = '/myOrders';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Here the axios.post works but the axios.delete does not. The page is getting redirected.
In the next code, again the axios.delete does not work.
axios.get('/api/getuser/')
.then(res => {
user_id = res.data.id;
console.log("Id Received");
})
.then(res => {
axios.delete("/api/cart/" + user_id + '/' + this.props.id)
.then(res => {
console.log("Product Deleted");
})
.then(res => {
window.location.href = '/cart';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Can someone please point out what the issue is or suggest a work-around?
It worked when I put the redirection statement in the first then function itself. It seems all the thens are triggered simultaneously. Because of this, the second then was triggered before the first.

How to Display quoteText from the response of this API Object

Random Quote
How to display the quoteText and quoteAuthor separately from this object for my random quote machine app.I have tried the standard way by writing {this.state.quote.quoteText}.
Here is the response object that I have got from my API.
1:[response object of API]
+Code Snippets
2:[code snippet-1]
3:[code snippet-2]
May be when the component is mounted your data is not yet fetched so here is one possible solution. On line number 37 where you have done this
{this.state.quote !== null && <p>{this.state.quote}</p>}
Instead Try this
this.state.quote.quoteText ? this.state.quote.quoteText : "";
Also on line number 23 where you have done this
axions.get("the url")
.then((res) => { this.setState({
quote: res.data
})
})
Add this line of code
.then((response) => response.json())
so your code will look like this
axions.get("the url")
.then((response) => response.json())
.then((res) => {
this.setState({
quote: res.data
})
})
**Even if that fails try this code that uses fetch **
fetch("the url goes here", {
method: 'GET'
})
.then((response) => response.json())
.then((data) => {
this.setState({
quote: data.response
})
you can call this fetch API directly in componentDidMount() lifecycle .

fetch api call data is not defined

Hey all I have a react app making a fetch api get request. When I console log the response after turning it into json it works fine but when I try to set state with data it says it is not defined. What am I missing?
componentDidMount() {
fetch('/api/logs')
.then(res => res.json())
// .then(data => console.log(data))
.then(this.setState({ Log: data }))
.catch(error => console.log(error))
}
The second chain expects a callback function, which setState is not.
componentDidMount() {
fetch('/api/logs')
.then(res => res.json())
.then((data) => this.setState({ Log: data })) // <---- wrap setState inside callback
.catch(error => console.log(error))
}

Resources