I am trying to develop the logic for a POST route handler in Express. I put the following together:
const headers = {
"Authorization":"TS Token asdfghjk-asdf-4567-fghjkl; tid=onfido-token";
"content-type": "application/json"
};
const params = {
"policy_request_id": "onfido_applicantandtoken"
};
app.get("/get_stuff", (req, res) => {
axios
.post("https://third/party/api", {
headers,
params
})
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
res.json("Error occured!");
});
}
});
I keep getting a 401 Unauthorized for the above. On Postman it works, but with the logic above I get a 401 Unauthorized, specifically in the logs I would get Header 'Authorization' not found or Could not parse authorization header. So I am unclear as to what could be going on with the header.
A lot of posts talk about req.headers, but my req.headers does not have the Authorization token and content-type in there, it has some other token that the API I am trying to connect to I assume needs to reach out to another API.
I have refactored it to look like this:
app.get("/get_stuff", (req, res) => {
axios
.post("https://third/party/api", params, headers)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
res.json("Error occured!");
});
}
});
And I am still getting the same exact error.
To be clear the params is not something that gets passed into the URL on Postman, but rather the body of the postman request.
I was able to get it to successfully connect by declaring a global axios default like so:
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
as documented here:
https://www.npmjs.com/package/axios#user-content-config-defaults
Related
I was testing get and post requests in jsfiddle to better understand cors and csrf.
const data = { name: 'example', password: 'password'};
fetch('http://localhost:3001', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hi')
})
app.post('/', (req, res) => {
console.log('received')
res.send('Received')
})
app.listen(3001, () => {
console.log('Listening on port', 3001)
})
Is it normal that the first preflight request fails when doing a post request?
Also, shouldn't the successful preflight request happen before the post request? (On the server side, the code handling the post request isn't executed (nothing logged in console), which means that the browser cancelled the post request. How would the browser know not to follow through with the post request without waiting for the preflight request to complete first?)
Update:
Tried it using a simple html page instead of jsfiddle and the preflight request doesn't fail, but it still happens after the fetch request
Edit:
Only one options request is received on the server
// debugging middleware, should be first router handler of any kind
let requestCntr = 0
app.use((req, res, next) => {
let thisRequest = requestCntr++
console.log(
`${thisRequest}: ${req.method}, ${req.originalUrl}, `,
req.headers
)
// watch for end of theresponse
res.on('close', () => {
console.log(
`${thisRequest}: close response, res.statusCode = ${res.statusCode}, outbound headers: `,
res.getHeaders()
)
})
next()
})
Edit 2: from console
For a get request, no network error is shown in the Network tab, but the same error appears in the console except with a status code
It seems that Chrome simply displays the preflight request with a network error in the Network tab if it's related to csrf. Since opaque GET requests are fine, this doesn't happen for GET requests. So in the case of a post request, even if "preflight" shows up twice, it's the same preflight request.
I'm trying to get axios working on a react native project to reach a backend but I am getting the Network Error issue that I just can't seem to debug.
const searchApi = async () => {
try {
let res = await axios.get('https://product.company.com/api/documents/invoices');
console.log(res);
} catch (err) {
console.log(err);
}
}
So if I was to do a get request to the example url provided via Thunder Client or Postman Client, I get the appropriate response of
{
"status": "401 error",
"message": "Token not found."
}
But when done through axios, I seem to get a network error. I'm a little unsure how I can debug this too to get more error logs.
Try with below code:
Replace with Your URL
var config = {
method: 'get',
url: 'https://reqres.in/api/users?page=1',
headers: {
'Content-Type': 'application/json'
}
};
axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
It's not a network error but an unauthorized error. You need to pass some authenticated token in the header.
Here is my code:
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am implementing Axios post request in my React Native application. I want to send formurlencoded parameters along with the header called cookie.
In cookie I am storing AWS token value to send. But I am not getting the response, it says cookie is not sent. The same URL with params working perfectly in Postman. How can I pass cookie in the header?
Try something like this Cookie: name=value.
Mozilla Web Docs
I am using axios in my Vue project, and one of the calls to my api involves a POST. Both my posts and gets require that the Authorization header be set with my token. All get requests work fine, but putting the exact same headers in axios.post results in a 403.
Here is my axios code:
axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
This always results in a 403 error, and checking my request headers show that the Authorization header is never sent. If I change axios.post to axios.get above (and add a GET method to my api code, in addition to the existing POST,OPTIONS), it will execute just fine. I suppose I could leave it this way, but I think it is bad practice to use a GET call when one really is performing a POST. Is there something I am missing about forming a POST request with axios?
Axios Post request assumes that the second parameter is data and third parameter is config.
Axios Get request assumes that the second parameter is config while the data is appended in URL.
You are sending data in the url which should be as second parameter(For POST request).
Code Should be:
var data = {
'uname': uname,
'umetaid': post.umeta_id,
'umetavalue': post.meta_value
}
var headers = {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
}
axios.post('https://my.example.org/myapi/meta',data,headers)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.
I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:
methods: {
getUser () {
this.$http.get('http://localhost:8000/api/user',
{
headers: {
'Authorization': 'Bearer eyJ0e.....etc',
'Accept': 'application/json'
}
}).then((response) => {
this.name = response.data.name
});
},
However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.
Based on the vue-resource readme I am trying this in my main.js:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
And then back in my component I now just have:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Problem:
When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?
Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:
When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.
However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.
It turns out my problem was the syntax for which I was setting the headers in the interceptor.
It should be like this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
While I was doing this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Add this option:
Vue.http.options.credentials = true;
And use the interceptors for global way:
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
});