here is my action of redux:
export const addToWishlist = (id) => async (dispatch, getState) => {
try {
const {
userLogin: { userInfo },
} = getState()
const config = {
headers: {
'Authorization': `JWT ${userInfo.token}`
}
}
const { data } = await axios.post(`/api/wishlist/add_to_wishlist/${id}/`, config
)
dispatch({
type: WISHLIST_ADD_ITEM,
payload: data
})
localStorage.setItem('wishlistItems', JSON.stringify(getState().wishlist.wishlistItemsFromStorage))
} catch (error) {
dispatch({
type: WISHLIST_ADD_ITEM_FAIL,
payload: error.response && error.response.data.detail
? error.response.data.detail
: error.message,
})
}
}
so i tried to send a post request to this api end point /api/wishlist/add_to_wishlist/${id}/ it says in response(from redux extension)
type:"WISHLIST_ADD_ITEM_FAIL"
payload:"Authentication credentials were not provided."
Authentication credentials we…provided.
but when I tried the same end point using postman it worked i.e. it add the item to wishlist.
What I tried
I tried to copy the token from console and paste it on postman it worked but again not on frontend
i even tried to hard copy the same token from postman to action code and it still says the same error
I tried change the config code and added content-type = applicaton/json but all in vain.
so can you please help me. Thanks .if you are curious here is view:
#api_view(['POST'])
#csrf_exempt
#permission_classes([IsAuthenticated])
def add_to_wishlist(request, id):
product = get_object_or_404(Product, _id=id)
if product.users_wishlist.filter(id=request.user.id).exists():
product.users_wishlist.remove(request.user)
else:
product.users_wishlist.add(request.user)
return Response('your item is add to the wishlist ')
in frontend please try like this.
const config = {
method: 'post',
url: `/api/wishlist/add_to_wishlist/${id}/`,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
data : {},
};
const { data } = await axios(config);
...
Related
Same question on GitHub - https://github.com/axios/axios/issues/2743
I have Axios in my Next.js project and sometimes I get an error due to interceptor when return the Promise.reject.
Error: Cannot set headers after they are sent to the client.
I encounter this problem when I make a request in getInitialProps. This happens very rarely when I restart the PC and open the page again.
Axios instance:
const instance = axios.create({
baseURL: 'https://my-api.com',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
})
instance.interceptors.response.use(undefined, error => {
if (error.response.status === 401) {
console.log("UNAUTHORIZED")
}
return Promise.reject(error) // <-- this cause the problem
})
Next.js Page example:
const Index = ({myData}) => {
return data.map(...)
}
Index.getInitialProps = async ({req}) => {
let myData
try {
const res = await API.get('/my-request', {
headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
})
myData = res.data
} catch (e) {}
return {myData}
}
This problem disappeared when I upgraded Axios 0.19.0 to 0.19.2 ¯_(ツ)_/¯
I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0
I've got an API where some of the parameters need to be given within the URL.
Example of how my api url looks like: https://www.server.com/api/actions/execute?auth_type=apikey&data={"Name": "name","Email" : "email"}
What my code looks like right now
register = async () => {
let data = {"Name":this.state.name, "Email":this.state.email}
data = JSON.stringify(data)
let URL = 'https://www.server.com/api/actions/execute?auth_type=apikey&data=';
fetch(URL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: data
})
.then((response) => response.text())
.then((responseText) => {
alert(responseText);
})
.catch((error) => {
console.error(error);
});
}
The response I get on my device:
{"code":"succes","details":{"userMessage":["java.lang.Object#2e56000c"],"output_type":void","id:"20620000000018001"},"message":"function executed succesfully"}
This is alle working fine when I test it in postman but I can't get it to work within React-Native. I've tried stuff like 'Content-Type':'application/x-www-form-urlencoded' already.
First install the package axios from the url https://www.npmjs.com/package/react-native-axios
Then create two service for handling get and post request so that you can reuse them
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
PostService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const PostService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.post(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
Sample code for using get and post services is given below
import { PostService } from './PostService';
import { GetService } from './GetService';
let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });
let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
If you need to pass parameters via URL you should use GET, if you use POST then the parameters should be passed in the body
I'm trying to call a GraphQL API that is in AWS Api Gateway. The call requires an x-api-key in the header to work.
I've successfully made this call in postman and using fetch.
fetch('ApiEndPoint', {
method: 'GET',
headers: {
'x-api-key': 'myApiKey'
},
body: JSON.stringify({query:'{getBook(book_id:"221"){author}}'}),
})
.then(res => res.json())
.then(res => console.log(res.data));
When I try to use the Apollo-Fetch query below, I get a 403 status and "Missing Authentication Token"
const { createApolloFetch } = require('apollo-fetch')
const uri = 'ApiEndPoint'
const query = `{getBook(book_id:"221"){author}}`
const apolloFetch = createApolloFetch({ uri })
apolloFetch.use(({ request, options }, next) => {
options.headers = {
'Content-Type': 'application/json',
'x-api-key': 'myApiKey'
}
next()
})
apolloFetch({ query, options }).then(result => {
console.log(result)
})
I am assuming that I am not passing the x-api-key properly - if this could work better for a different GraphQL Client I would love other suggestions!
I have an action that creates a fetch to POST a client back to the API.
I send a JWT in the "headers" which by itself is not the problem as its also used in a GET that works just fine... but not in a POST. Here is my action:
export const createNewClient = (payload) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_CREATE_NEW_CLIENT, payload })
const jwt = getJwt()
if (!jwt) {
throw new Error('No JWT present')
}
const token = jwt.access_token
const headers = new Headers({
'Authorization': `bearer ${token}`
})
debugger
const task = fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_CREATE_NEW_CLIENT, payload: data })
dispatch({
type: SAVE_MESSAGE, payload: {
message: "Successfully saved client",
type: 'success'
}
})
})
.catch(error => {
//clearJwt()
dispatch({ type: ERROR_CREATE_NEW_CLIENT, payload: error.message })
dispatch({ type: SAVE_MESSAGE, payload: { message: error.message, type: 'error' } })
})
addTask(task)
return task
}
I tried modifying the headers to include UTF-8 like so.
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
However this just gave me 401 Unauthorized which means that by using this it is the correct media type but now wont be accepted.
That same JWT works fine in a Fetch GET command so the JWT itself is not the problem - I believe it might be the way I am writing the "Fetch".
Now I do the same thing in Postman and I get through but not with this Fetch...
What have I missed or incorrectly structured for a Fetch POST so that JWT is accepted etc
If it works as in the provided image
then the following will work
fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Authorization': `bearer ${token}`,
'Content-Type': 'application/json',
}
})