$axios.onError is not a function - axios

I am using nuxt community axios module.
And this is my plugin inside plugins/axios.js
Everything was working fine but now all of a sudden I get the error $axios.onError is not a function
Here is my plugins/axios.js
export default function({ $axios, store, redirect }) {
$axios.onError(error => {
if (error.response.status === 422) {
store.dispatch("validation/setErrors", error.response.data.errors);
return redirect("/login");
}
return Promise.reject(error);
});
$axios.onRequest(config => {
config.headers["Content-Type"] = "application/json";
config.headers["Access-Control-Allow-Origin"] = "*";
store.dispatch("validation/clearErrors");
});
}

It was a weird issue so I went back to my previous project and used the exact versions of those packages and it worked!
I had to update package.json for the following packages from this:
"#nuxtjs/auth": "^4.5.3",
"#nuxtjs/axios": "^4.5.2",
// to
"#nuxtjs/auth": "^4.5.2",
"#nuxtjs/axios": "^5.3.3",

Related

How to create Strapi entries in Nextjs with a Form (Apollo and GraphQL)

I am trying to create new Strapi entries in Nextjs by submitting a form using Apollo client and GraphQL.
I tried a lot of diffrent things with my limited knowledge and was not able to make it work. While researching the topic I realized that most people are using the "useMutation" hook. It never worked though (also when using "useQuery" for queries). So I used a similar approach as for queries because they work.
queries: client.query | mutations: client.mutate
What I have tried:
// GraphQL that works in the Strapi playground
const TEST1 = gql`
mutation CreateMitgliedanmeldung($name: String!) {
createMitgliedanmeldung(data: { name: $name }) {
data {
attributes {
name
}
}
}
}`;
export default function MitgliedWerden() {
const formState = {
name: ''
};
function updateFormState(key, value) {
formState[key] = value;
}
function submit2() {
console.log(formState.name);
client.mutate({
variables: { name: formState.name },
mutation: TEST1,
})
}
return (
<div>
<form onSubmit={submit2()}>
<input onChange={e => updateFormState('name', e.target.value)} id="name"></input>
<button type="submit">Mitglied werden 1</button>
</form>
</div>
)
}
The code above creates new entries but there are multiple problems:
Variable "name" is not present in the new entry but can be console logged inside "updateFormState" function
(same mutation works fine inside graphql playground)
Form is submitted when page is reloaded/loaded
When submitting the page reloads (this is fine if the other problems are gone)
To fix the reload problem I added the following and called it onSubmit.
// calling this onSubmit instead of submit2 function
const newsubmit = (e) => {
e.preventDefault();
submit2()
};
Now submitting or reloading the page does not create a new entry but I get the console.log with the correct value. It seems like the "client.mutate" is broken or can't work in those conditions.
I was not able to find a lot about the ".mutate" function from apollo and the more often used "useMutation" hook did not work at all for me. Using "client.query" works fine.
Apollo Client:
import { ApolloClient, InMemoryCache } from "#apollo/client"
const defaultOptions = {
query: {
fetchPolicy: "no-cache",
},
}
const client = new ApolloClient({
uri: process.env.STRAPI_GRAPHQL_URL,
headers: { "Authorization": process.env.STRAPI_TOKEN },
cache: new InMemoryCache(),
defaultOptions,
});
export default client
Dependencies:
"#apollo/client": "^3.6.9",
"#apollo/react-hooks": "^4.0.0",
"graphql": "^16.5.0",
"graphql-request": "^4.3.0",
"next": "12.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",

Cannot read property 'Authorization' of undefined with Nuxt Auth & Axios

I have been using nuxt/auth-next and axios modules with nuxt project since last 3-4 months, everything was working fine since yesterday but now whenever I try to send axios request to public APIs without passing Authorization in headers, I get this error
Cannot read property 'Authorization' of undefined with Nuxt Auth & Axios
Attached is a screenshot of the page
below is my code in index.js store file
export const actions = {
async nuxtServerInit({ commit }, context) {
// Public profile
if (context.route.params && context.route.params.subdomain) {
context.$axios.onRequest((config) => {
config.progress = false
})
let { data } = await context.$axios.get(
`users/get_user_data_using_subdomain/${context.route.params.subdomain}`,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
)
await context.store.dispatch('artists/setPublicProfile', data.user_data)
}
},
}
This happend to me to when I was using context.app.$axios instead of context.$axios within a injection
Nuxt server is looking for config.headers.common.Authorization.
The example below is a quick win for you:
let { data } = await context.$axios.get(
`users/get_user_data_using_subdomain/${context.route.params.subdomain}`,
{
headers: {
common: null, // or something like this: context.$axios.defaults.headers?.common
'Content-Type': 'multipart/form-data',
},
}
)

Cancelling promise in nuxt-axios response interceptor

Basically, my question is the exact one here https://github.com/axios/axios/issues/583. It can be done via throw new axios.Cancel('Operation canceled by the user.');.. But how can I do this in nuxt axios module?? I can not see it in the document and I tried $axios.Cancel('Error') but returned $axios.Cancel is not a constructor
Basically, the something like the snippet below is what I am looking for:
axios.interceptors.response.use(function (response) {
throw new axios.Cancel('Operation canceled by the user.');
}, function (error) {
return Promise.reject(error);
});
Emphasis on throw new axios.Cancel
While #nuxtjs/axios does not expose axios.Cancel, you could still import axios directly to get that symbol. Note axios is already a dependency of #nuxtjs/axios, so no extra dependency necessary.
Example (tested with #nuxtjs/axios v5.11.0):
// plugins/axios.js
import { Cancel } from 'axios'
export default function ({ $axios }) {
$axios.onResponse((response) => {
if (response.code !== 200){
throw new Cancel(response.msg)
}
})
}
With nuxt/axios v5.8.0 IsCancel available
v5.8.0 add CancelToken and isCancel to axios instance
Seems like nuxt-axios does not have any exact equivalent but I found a work around.
plugins/axios.js
export default function({ $axios, req, store, redirect, app }, inject) {
// const source = $axios.CancelToken.source()
const timeout = process.env.API_TIMEOUT || 10000
const errorHandling = function(error) {
console.log(`API ${error}`)
return new Promise(() => {})
}
$axios.onResponse((response) => {
// Any condition that could be considered an response based on standard response
if(response.code !== 200){
throw response.msg
}
})

How to set HTTP headers win axios.interceptors?

I copied the following code from Amazon Cognito Vuex Module examples to my Vue.js app:
axios.interceptors.request.use(async config => {
const response = await store.dispatch('getUserSession');
if (response && response.accessToken && response.accessToken.jwtToken) {
config.headers.awsToken = response.accessToken.jwtToken;
}
return config;
});
and expected to see in the request headers something like
awsToken: AzWDF....
, but actually I am getting:
Why 'awstoken' goes to 'Access-Control-Request-Headers' and why it does not have a value?
I also tried
config.headers.common['awsToken'] = response.accessToken.jwtToken;
but with the same result.
It is not a problem of AWS, because response.accessToken.jwtToken has a valid non-empty value.
EDIT1: and even this example does not work in my app and gives the same result:
axios.interceptors.request.use(config => {
config.headers['Authorization'] = 'Bearer XYZ';
return Promise.resolve(config);
},
(error) => {
return Promise.reject(error);
});
EDIT2: I found similar post.

Getting user app token using react-native facebook SDK

I've gotten facebook login working using the new https://github.com/facebook/react-native-fbsdk, however I can't seem to get the user token which is usually returned in the response. Anyone found a way to get this information? The other SDK's https://github.com/magus/react-native-facebook-login returns it on the login request but the new FB sdk doesn't, and the documentation on the github page doesn't mention it anywhere.
Found the answer after some more digging. You need to use the fbsdkcore to access the user token. Heres how you use it.
var FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
FBSDKAccessToken.getCurrentAccessToken((token) => {
console.log(token.tokenString);
})
}
}
}}
onLogoutFinished={() => console.log('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
You don't need a third party module (react-native-fbsdkcore)
The package (react-native-fbsdk) has instructions on it's Github page: https://github.com/facebook/react-native-fbsdk#usage
After you've logged the user in, you can fetch the access credentials as follows:
import { AccessToken } from 'react-native-fbsdk';
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString())
})