Possible Unhandled Promise Rejection (id: 0): TypeError: adapter is not a function. (In 'adapter(config)', 'adapter' is undefined)? - axios

when i request login api the error is:
Possible Unhandled Promise Rejection (id: 0):
TypeError: adapter is not a function. (In 'adapter(config)', 'adapter' is undefined)
dispatchRequest#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:126225:19
tryCallOne#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27056:16
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27157:27
_callTimer#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30596:17
_callImmediatesPass#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30635:17
callImmediates#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30852:33
__callImmediates#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2736:35
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2522:34
__guard#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15
flushedQueue#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2521:21
flushedQueue#[native code]
callFunctionReturnFlushedQueue#[native code]
running environment:
react-native#63
axios
axios config:
import axios from 'axios';
import {getAccessToken} from './util'
const service = axios.create({
baseURL: '/',
timeout: 6000
})
var token;
service.interceptors.request.use(config => {
token = getAccessToken()
if (config.headers['Content-Type']) {
console.log(config.headers['Content-Type'])
} else {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
}
config.headers['Authorization'] = `Bearer ${token}`
return config
}, error => {
return Promise.reject(error)
})
service.interceptors.response.use(response => {
return response.data
}, error => {
return Promise.reject(error)
})
export {service as axios}
request login:
const {code, message, data} = await login({phone, password})
setLoading(false)
if (code === 1) {
saveAccessToken(data.access_token)
ToastAndroid.showWithGravity(
message,
ToastAndroid.SHORT,
ToastAndroid.CENTER
)
getInfo(data.access_token)
navigation.navigate('Home');
} else {
setErrortext(message)
return
}
storage example:
const saveAccessToken = async (accessToken) => {
try {
await AsyncStorage.setItem('access_token', accessToken)
} catch (error) {
return error
}
}
error show:
when i not debugger mode and get this error, if is debugger mode running ok. i don't know where the error? please help me, thanks!

i find why the error.
i use rn-fetch-blob send http request, this package use fetch, but i use axios and ternimal tips:
Require cycle: node_modules\rn-fetch-blob\index.js -> node_modules\rn-fetch-blob\polyfill\index.js -> node_modules\rn-fetch-blob\polyfill\Blob.js -> node_modules\rn-fetch-blob\index.js
i remove this package and send http request is ok!

Related

How to use axios response error.config to retry the request?

I'm following a tutorial that uses an interceptor to retry a request with an authorization token, the code is like this:
import axios from "axios";
axios.defaults.baseURL = "http://localhost:8000/api/";
axios.interceptors.response.use(resp => resp, async error => {
console.log('error', error)
if (error.response?.status === 401) {
const {data, status} = await axios.post('refresh', {}, {withCredentials: true});
if (status === 200) {
axios.defaults.headers.common['Authorization'] = `Bearer ${data.accessToken}`
}
return axios(error.config) ;
}
return error;
});
In the tutorial this seems to work fine, but in my machine I'm getting this error :
error DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function(header, parser) {
header = normalizeHeader(header);
if (!header)
return void 0;
const key = findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils_default.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils_default.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError("parser must be boolean|regexp|function");
}
}' is not a valid HTTP header field value.
at setRequestHeader (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:1208:17)
at Object.forEach (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:89:10)
at dispatchXhrRequest (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:1207:21)
at new Promise (<anonymous>)
at xhrAdapter (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:1111:10)
at Axios.dispatchRequest (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:1424:10)
at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:1666:33)
at wrap (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ea4ef45:16:15)
at http://localhost:5173/src/intereceptors/axios.ts?t=1665639283918:10:12
at async http://localhost:5173/src/pages/Home.svelte:74:20
if I replace return axios(error.config); with a regular request then everything works :
const userdata = await axios.get('http://localhost:8000/api/user')
return userdata;
I'm wondering if since I'm using a newer version of axios, things have changed and now this doesn't work anymore, or is there a way to make it work with axios(error.config)

Express and MongoDB, how to manualy throw the error in the route controllers?

I'm new to the Express, and I'm trying to apply some error handling at the top level.
In my controllers file, I have a controller to get all tours.
exports.getAllTours = async (req: Request, res: Response) => {
//Execute query
const features = new APIFeatures(Tour.find(), req.query)
.filter()
.sort()
.limitFields()
.paginate();
// Endpoint: http://localhost:8000/api/v1/tours
// Enter a wrong URL here will not even trigger the console.log function.
// But I want to throw the error right here, not in the app.all('*')
console.log("features", features);
if (!features) {
throw new NotFoundError("Tours Not Found");
}
//same problem here.
const tours = await features.query;
console.log("tours", tours.length);
if (!tours) {
throw new NotFoundError("Tours Not Found");
}
res.status(200).json({
status: "success",
result: tours.length,
data: {
tours,
},
});
};
I have a CustomError class that extends the Error class like this.
const httpStatusCode = require("./httpStatusCode");
class CustomError extends Error {
constructor(message: string, statusCode: number, description: string) {
super(description);
//Object.setPrototypeOf(this, new.target.prototype);
this.message = message;
this.statusCode = statusCode;
}
}
module.exports = CustomError;
class NotFoundError extends CustomError {
constructor(message, statusCode) {
super(message, statusCode);
this.message = message;
this.statusCode = httpStatusCode.NOT_FOUND;
}
}
module.exports = NotFoundError;
Also an error handling middleware:
import { NextFunction, Request, Response, ErrorRequestHandler } from "express";
module.exports = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || "error";
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
};
In the end, I use the errorHandler middleware in the app to catch all the errors.
However, the problem is all the errors in the getAllTours controller will not be thrown, instead, they will be thrown in the app.all():
app.use("/api/v1/tours", tourRouter);
app.all("*", (req: Request, res: Response) => {
throw new NotFoundError("Page Not Found");
//next(new AppError(`Can't find ${req.originalUrl} on this server`, 404));
});
app.use(errorHandler);
I know since the endpoint has been changed and thrown in the app.all() make sense. But how can I manually throw an error in the getAllTours controller?
I use express-async-error so I could use the throw keyword in the async function.
I figure it out.
Handle Express async error
I had no idea Express version 4 could not handle the async errors by simply throwing a new error. I'm still not sure if Express Version 5 as it now could handle it.
But I use ExpressJS Async Errors to solve this issue in the end.

Fiware ngsi-javascript node-fetch error when creating entity

I use this module : https://github.com/cenidetiot/ocb-sender
I have one file txt and i read line by line. Each line is a new entity. Sometimes if one of this entity has big information i get this get this error when trying create entity:
This is the code to create entity:
createEntity(entity, headers = {}){
this.addTimeStampEntity(entity);
let t = this
const promise = new Promise(function (resolve, reject) {
headers['Content-Type'] = 'application/json';
const options = { // assign the request options
method: 'POST',
headers: headers,
body: JSON.stringify(entity)
};
fetch(t._URLContext+'/entities', options)
.then(function(res) {
resolve({status : res.status, message:"Entity
})
.catch(function(err){
reject(new Error(`An error has occurred with the creation of the entity: ${err}`))
});
})
return promise; // returns the promise
}
And i get this error:
Error: An error has occurred with the creation of the entity:
FetchError: request to http://192.168.1.5:1026/v2/entities failed, reason: socket hang up
at /Users/helderoliveira/MyApps/MicroServices/connector-fiware/node_modules/ocb-sender/lib/OCB.js:209:28
So i try use timeout but doesn´t work.
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
</pre></code>
can you help me understand this problem ?
Thank you!

How to get axios error response INTO the redux saga catch method

With axios the code is:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => err);
}
And then I'm using this with redux-saga like this:
function* createBlaBlaFlow(action) {
try {
const response = yield call(createBlaBla, action.payload);
if (response) {
yield put({
type: CREATE_BLA_BLA_SUCCESS
});
}
} catch (err) {
// I need the error data here ..
yield put({
type: CREATE_BLA_BLA_FAILURE,
payload: 'failed to create bla-bla'
});
}
}
In case of some error on the backend - like invalid data send to the backend - it returns a 400 response with some data:
{
"code":"ERR-1000",
"message":"Validation failed because ..."
"method":"POST",
"errorDetails":"..."
}
But I don't receive this useful data in the catch statement inside the saga. I can console.log() the data in the axios catch statement, also I can get it inside the try statement in the saga, but it never arrives in the catch.
Probably I need to do something else? ... Or the server shouldn't return 400 response in this case?
So, I came up with two solutions of this problem.
===
First one - very dump workaround, but actually it can be handy in some specific cases.
In the saga, right before we call the function with the axios call inside, we have a variable for the errors and a callback that sets that variable:
let errorResponseData = {};
const errorCallback = (usefulErrorData) => {
errorResponseData = usefulErrorData;
};
Then - in the axios method we have this:
export const createBlaBla = (payload, errCallback) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => {
if (err && err.response.data && typeof errCallback === 'function') {
errCallback(err.response.data);
}
return err;
});
}
This way, when we make request and the backend returns errors - we'll call the callback and will provide the errors from the backend there. This way - in the saga - we have the errors in a variable and can use it as we want.
===
However, another solution came to me from another forum.
The problem I have is because in the method with the axios call I have catch, which means that the errors won't bubble in the generator. So - if we modify the method with the axios call like this:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
}
Then in the catch statement in the saga we'll have the actual backend error.
Hope this helps someone else :)
In your API call you can do the following:
const someAPICall = (action) => {
return axios.put(`some/path/to/api`, data, {
withCredentials: true,
validateStatus: (status) => {
return (status == 200 || status === 403);
}
});
};
Please note the validateStatus() part - this way when axios will encounter 200 or 403 response, it will not throw Error and you will be able to process the response after
const response = yield call(someAPICall, action);
if (response.status === 200) {
// Proceed further
} else if (response.status === 403) {
// Inform user about error
} else {
...
}

Convert Http Response to Json object Ionic 3

The below response is returned upon calling the signup function
Response {_body: "string(85) "{"message":"A customer with the same email
already exists in an associated website."}"↵", status: 200, ok: true,
statusText: "OK", headers: Headers, …}
headers: Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://127.0.0.1/sandbox/M2API/signup/signup"
_body: "string(85) "{"message":"A customer with the same email already exists in an associated website."}"↵"
__proto__: Body
Signup Function:
signup() {
this.authServiceProvider.postData(this.userData, "signup").then((result) => {
this.responseData = result;
console.log(this.responseData);
if( (JSON.stringify(this.responseData._body)) != "" ) {
this.navCtrl.setRoot(HomePage);
} else {
console.log("User already exists");
}
}, (err) => {
//connection failed error message
console.log("something went wrong");
});
}
When i do console.log(JSON.stringify(this.responseData)); backslahes are added to json object
How to avoid that and access message in the response.
Use this
import 'rxjs/add/operator/map';
this.http.get('YOUR_API_ENDPOINT').map(res => res.json()).subscribe(data => {
console.log(data);
});