POST Request works with Postman but fails in fetch? - javascript

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

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.

Cant get data from express server

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

Send POST request using fetch Type Error: Failed to fetch

I'm trying to make a post request from a webpage to a Wildfly Camunda server to start a task. It works using postman with localhost:8080/engine-rest/message, but when I use the webpage all I get is Type error: failed to fetch. I have tried just using localhost:8080/engine-rest/message but gets:
Fetch API cannot load localhost:8080/engine-rest/message. URL scheme must be "HTTP" or "HTTPS" for CORS request.
/* And */
Error: TypeError: Failed to fetch at HTMLFormElement.<anonymous>
And if I set mode : no-cors I get Fetch API cannot load localhost:8080/engine-rest/message. URL scheme "localhost" is not supported. and Error: TypeError: Failed to fetch at HTMLFormElement.<anonymous>
const form = document.getElementById('myForm');
form.addEventListener('submit', function() {
// alert("Request sent");
const urlHttp = 'http://localhost:8080/engine-rest/message';
const url = "localhost:8080/engine-rest/message";
const data = {
messageName: 'start',
businessKey: '7'
};
// send POST request
fetch(urlHttp, {
method: 'POST',
// mode : 'no-cors',
headers: {
'Content-Type': 'application/json; charset=UTF-8;',
// 'Accept' : 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
});

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.

axios.post works in chrome but not in firefox

Hello Everybody!
I have a SPA made with vuejs, and also using webpack. To make http calls, i am using axios, but something really strange is happening ...
When i use the spa on CHROME everything works fine, but ANY other browser (safari, firefox, iosSafari) gives me the following error:
Error: Network Error
Stack trace:
createError#webpack-internal:///34:16:15
handleError#webpack-internal:///33:88:14
Error shown in console (more details)
The code that makes this call is:
const rep = localStorage.getItem('rep')
const token = localStorage.getItem('token')
const config = {
headers: {
'Content-Type': 'application/json',
'x-access-token': token
}
}
axios.post('localhost:1234/statusproducao', { representante: rep }, config)
.then((response) => {
Loading.hide()
this.statusPinos = response.data.statusProducao
})
.catch((error) => {
Loading.hide()
console.log(error)
})
Looking at devtools --> network, i can see that the browser didn't make the post request, and the error shown before, comes from the .catch(error) from axios.post
The const rep, and token are both strings.
What am i missing ?
I added the 'x-access-token' header on my cors, and in the routes, i needed this too:
'x-access-token': token
server.opts(/\.*/, function (req, res, next) {
res.send(200)
next()
})

Categories

Resources