axios.post works in chrome but not in firefox - javascript

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()
})

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.

Axios POST request returns 404 error when sending to Node.js API

I am developing a web application using a React frontend and a Node.js backend. The frontend sends a POST request to the backend using Axios like this:
Register.js
...
handleSubmit = (e) => {
e.preventDefault();
const { email, password, name, dateofbirth } = this.state;
const user = { email, password, name, dateofbirth };
const url = "http://localhost:9000/register";
axios
.post(url, user, {
headers: {
"Content-Type": "application/json",
},
})
.then((response) => console.log(response))
.catch((error) => {
console.error("You have made a big error. " + error);
console.log(user);
});
};
...
While the backend receives the request like this:
./routes/register.js
...
router.post("/register", async (req, res) => {
console.log("Inside Home Login");
res.writeHead(200, {
"Content-Type": "application/json",
});
console.log("Users : ", JSON.stringify(users));
res.end(JSON.stringify(users));
})
...
However I get the error "POST http://localhost:9000/register 404 (Not Found)" upon trying to send anything.
My guess would be that you are routing in your index.js. If you can provide a code sample to figure it out.
If so, the thing is defining a routing like,
app.use('/register', yourImportedVariable);
does define a route at http://localhost:9000/register.
So, if in your routes/register.js file you define a GET endpoint with '/register' your front-end call must be http://localhost:9000/register/register
To fix it, either rename your route as '/', or fix your front-end call with the above url.

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

Django Rest Framework CORS blocking XMLHttpRequest

I have set up my CORS policy using Django-cors-headers with the following settings:
APPEND_SLASH=False
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'localhost:3000',
'localhost'
)
I have also added it to installed_apps and middleware.
Now I am making a React app for the front end and using AXIOS for my API requests. When I make an API request to log in to my app the CORS policy allows it. But, if I make an API request that requires a Token, I get:
Access to XMLHttpRequest at 'localhost:8000/api/TestConnection/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
It seems that I need to allow XMLHttpRequest for supported protocol schemes but I cannot find anything in the pypi documentation about this.
EDIT:
Here is the AXIOS Request:
axios.post("localhost:8000/api/TestConnection/",
{headers:
{
'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
}
},
{
testString: 'Hello API'
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
})
Thank you!
I Have had a similar issue with a ReactNative app which was happening due to ReactNative using IP 10.0.2.2 for localhost (I do not remember the details or why). I solved it by adding to my class.
componentWillMount() {
axios.defaults.baseURL = 'http://10.0.2.2:8000/api/';
axios.defaults.timeout = 1500;
}
I do not know if this is the right IP but may be worth looking at.
EDIT
handleRequest() {
const payload = { username: this.state.username, password: this.state.password }
axios
.post('login/', payload)
.then(response => {
const { token, user } = response.data;
// We set the returned token as the default authorization header
axios.defaults.headers.common.Authorization = `Token ${token}`;
// Navigate to the home screen
Actions.main();
})
.catch(error => {
console.log(error)
});
}
By saving the Token within my headers it is always sent.
The error says "from origin 'http://localhost:3000'" and to "check the cors policy"
I see your CORS policy is
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'localhost:3000',
'localhost'
)
maybe try providing the full http url. so
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'http://localhost:3000',
'localhost'
)
I solved it! The solution was very simple(of course),
For the request I needed to use part of #HenryM 's solution.
First I needed to establish the default url:
axios.defaults.baseURL = 'http://127.0.0.1:8000/api/';
Then I save the payload and header to const variables:
const header = {
headers:{
'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
}
}
const payload = {
testValue: "Hello API"
}
Finally, the main issue was that my parameters were in the wrong order:
axios.post("TestConnection/", payload, header)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
Apparently the propper order, at least when using Django Rest Framework, is payload then header!!!
Thank you to everyone who tired to help!
This was the article that ended up helping me: https://www.techiediaries.com/django-vuejs-api-views/

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.

Categories

Resources