Cant get data from express server - javascript

I am trying to send a GET request and receive a response on my client side (react).
On my express server:
app.get('/', function (req, res) {
res.send('Hey, I came from the express server');
})
When I use postman to sent the request I receive a good answer:
So I don't think the problem is with the server.
A problem:
When I try to send the request using react like this:
const getData = () => {
fetch("http://localhost:8081", {
method: "GET",
mode: 'no-cors'
}).then(response => console.log(response));
}
For some reason the response status is 0 and not 200 (I am receiving status code of 200 when checking this request with postman and also on the chrome network tab).
In addition, if I try to print response.body it will be null.
The response:
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
[[Prototype]]: Response
What am I doing wrong here?

You can add a proxy property to your package.json:
"proxy": "http://localhost:8081",
And then just use / as your fetch endpoint.
fetch('/'...

You need to transfer your response to an text or json like:
const getData = () => {
fetch("http://localhost:8081", {
method: "GET",
mode: 'no-cors'
}).then(response => response.json()).then(data => console.log(data))
}
Besides .json() there are even more methods. Its everything written down in the docs. You just need to google it:
https://developer.mozilla.org/en-US/docs/Web/API/Response#methods

Related

Nodejs PUT/PATCH is not working with axios and request but same works from Postman

I am trying to make some modifications to my Rest API by making the PUT request using request package but it does not seem to work so. Although I am able to make the modifications to the same API using the same JSON body using the Postman. Also, I am not getting any errors so not understanding what's wrong.
Since request was not working, I tried axios even with that no response no error. Following is my sample code which is making request to my Rest API:
const request = require('request');
const axios = require('axios');
const https = require('https');
request(
{
url: testIdUrl,
method: 'PUT',
agentOptions: {
rejectUnauthorized: false
},
headers: [{
'content-type': 'application/json',
body: JSON.stringify(requestBody)
}]
},
function(error, response, body) {
if(error){
console.log("SOMETHING WENT WRONG")
console.log(error)
}
console.log("RESPONSE FROM TEST ID PUT")
})
axios.put(testIdUrl, requestBody)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
Can someone please help me understand what's wrong with the code? Does my Rest API include all the tokens and information? When I use the same requestBody and URL then its works in POSTMAN.

POST Request works with Postman but fails in fetch?

I created backend where it will accept requests to the following url
http://10.1.0.1/cgi-bin/api/write_config
With Postman I get the appropriate response but when I try the same thing with fetch, I get a network error
This is my code:
fetch ('http://10.1.0.1/cgi-bin/api/write_config', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
param1: 'attr1',
param2: 'attr2',
param3: 'attr3',
}),
})
.then(response => {
console.log(response.json())
return response.json()
})
.then(data => {
console.log(data)
})
.catch(e => {
console.log('In catch block')
console.log(e)
})
These are the header I'm getting from the response (in Postman):
Content-Type: application/json
Access-Control-Allow-Origin: *
I'm getting the following error (in Javascript):
{ [TypeError: Network request failed] line: 24117, column: 31,
sourceURL:
'http://localhost:8081/index.delta?platform=android&dev=true&minify=false'
}
Edit:
I configured the Raspberry Pi in the same way in which I configured the other device then the output is correct. Is it some certificate issue with Javascript?
If you are using the Android Emulator try to use your IP Address instead of 10.1.0.1 - I had network request errors too but it worked with my IP.
did u tried console.log(body) ? sometimes JSON not work. if u don't have problem with body . I'm sure header is wrong

How do I make a post request from a react front-end to a node back-end? Getting 404

I'm trying to make a simple website where users can post things to learn the MEAN stack. When I'm handling the POST request, which will be handled and inputed to the MongoDB server through the back-end. React is on port 3000, and the server is on 5000. How do I make the request go from 3000 to 5000? My request works through Postman but not using axios. I added the proxy to the client-side package.json.
I've tried changing the proxy, adding CORS, changing to every single possible route. Nothing works.
Back-end:
router.post('/api/req',(req,res)=>{
const newPost = new Post({
title: req.body.title,
description: req.body.description
})
newPost.save().then(()=>{
console.log('Item added to database!')
});
})
Front-end:
axios({
method: 'post',
url: '/api/req',
data: {
title: this.state.title
},
validateStatus: (status) => {
return true;
},
}).catch(error => {
console.log(error);
}).then(response => {
console.log(response);
});
"proxy": "http://localhost:5000/" - package.json
I'm expecting the POST request to go through, and for the title to be inputed into the database. Instead, I get the error: Failed to load resource: the server responded with a status of 404 (Not Found)
The error is coming from localhost:3000/api/req, and it should be proxying port 5000. Also, the actual route is routes/api/req.js.
You will have to pass the complete url:
axios({
method: 'post',
url: 'http://example.com:5000/api/req',
data: {
title: this.state.title
},
validateStatus: (status) => {
return true;
},
}).catch(error => {
console.log(error);
}).then(response => {
console.log(response);
});

Vue.js Fetch throws 404 and api response

I can't make a POST request in Vue.js. It was giving me CORS issues, but I added
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
to the API and they went away. I can get valid responses from the API using Postman while using the same email and password (Postman ignores CORS).
Here is my Fetch request:
<script>
export default {
data () {
return {}
},
methods : {
login : function () {
console.log('Logging in');
// axios({
// method : 'post',
// url : 'https://www.example.com/login',
// headers : {'content' : 'application/json'},
// data : {
// email : 'emailHere',
// password : 'passwordHere'
// }
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
fetch('https://www.example.com/login', {
method: 'POST',
body: JSON.stringify({
email : 'emailHere',
password : 'passwordHere'
})
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err))
}
}
}
</script>
https://www.example.com/api/v1/authenticate/login 404 (Not Found)
{status: false, message: "Invalid credentials"}
I tried Axios, and still gives me 404, but not the "Invalid Credentials" response.
In other applications I have used jquerys ajax successfully with the same API, so the API seems to allow javascript requests. But Fetch and Axios don't like it.
I have a Login.vue component that has a button
<a id="login-btn" #click.prevent="login">{{ $t('loginPage.loginButtonText') }}</a>
Any help would be appreciated! Thanks!
You are missing Content-Type header. Try setting headers in your request. Fetch demands that you set headers explicitly since it is a low-level API. Your server may reject as it doesn't recognize appropriate Content-Type. Try this:
fetch('https://www.example.com/login', {
method: 'POST',
// THIS IS IMPORTANT
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
}),
body: JSON.stringify({
email : 'emailHere',
password : 'passwordHere'
})
})
Also, remember two things with fetch:
First getting 404 using fetch doesn't mean that your request has failed. If a server responds 4xx or 5xx error, then fetch is considered successful. Only when a network error occurs, fetch is rejected. So if you get 404, it means the request has reached server but there is a problem with the client side.
Second, try setting mode to cors in you fetch request. Thought the default value of mode is cors.

Fetch Request Completes Successfully, but Response Object Empty

I have a fetch request within the componentDidMount() method of a React component:
const request = new Request(url, {
mode: 'no-cors',
method: 'get',
headers: {
Accept: 'application/json'
}
});
fetch(request)
.then(function(response) {
console.log('Response: ', response);
return response.text();
})
.then(function(data) {
// _this.setState({ data: data });
console.log('Success: ', data);
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
When the Component loads, I can see the Request being made in the Console and the proper data being returned; however, my Response object is always empty:
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, bodyUsed: false }
response.text() returns null, and I'm really uncertain what is going on. I've used the same method before and not had this problem, so I'm uncertain if it's different because of the third-party data source or what.
Any ideas?
I suggest you to follow the comments below the question:
sideshowbarker says
If the reason you’re using mode: 'no-cors' is because the server doesn’t send the Access-Control-Allow-Origin response header in its responses, then mode: 'no-cors' is not the way to fix that. The only way to fix it properly is to either configure the server to send Access-Control-Allow-Origin response header or else change your frontend JavaScript code to make you request through a proxy instead. follow this link...

Categories

Resources