Fiware ngsi-javascript node-fetch error when creating entity - fiware-orion

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!

Related

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.

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

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!

Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in

I am getting ** Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in 5f8425a33a14f026f80133ed** where 5f8425a33a14f026f80133ed is the id passed to the axios url
I want to display the services based on the user id. My url works perfectly in postman but when i access it from the veux store it gives an error.
services.js (store)
import axios from 'axios';
const state = {
services : {},
status: '',
error: null
};
const getters = {
services : state => { return state.services }
};
const actions = {
async fetchServices({commit}, userId) {
let res = await axios.get('http://localhost:5000/api/services/displayUser' , userId)
commit('setProducts', res.data)
return res;
}
};
const mutations = {
setProducts (state, items) {
state.services= items
},
};
export default {
state,
actions,
mutations,
getters
};
This is how I am calling the action :
computed: {
...mapGetters(["services"]),
},
methods: {
...mapActions(["fetchServices"]),
getData(){
this.fetchServices(this.user._id)
},
},
async created() {
await this.getProfile();
await this.getData();
}
The axios route is defined as
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
the error screenshot :
Error screenshot
GET request should not have a body. Either use query params, indicate an id in a path, or use POST request.
In case of query params this may look like this:
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { userId })
router.get('/displayUser', (req,res) => {
const query = user = req.query;
Services.find(query)
.exec((err, services) => res.json(services))
})
This worked for me too:
In front end: Vue Js
let res = axios.get("http://localhost:3000/api/v1/role/getRoleByName",
{ params: { roleName: "name of role you want to send as params" },
});
In back end: Node Js
router.get('/getRoleByName', (req,res)=>{
let roleName = req.query.roleName;
roleModule.getRoleByName(roleName).then(data =>{
response.json(res,data)
}
).catch(err=> {
response.badRequest(res, err);
})
});
it's a silly mistake axios.post req.
async addTodo({ commit }, title) {
try {
const res = await axios.post(BASE_URL, { title, complete: false });
commit("newTodo", res.data);
} catch (err) {
console.log(err.message);
}
},

Ionic formData append showing null in server

I am trying to upload an image using formData. The api is working fine. But the data is displaying null in the server.
My function is
capture_dl_front(){
this.camera.getPicture(this.cameraOptions)
.then(imageData => {
this.customer.dl_front = normalizeURL(imageData);
this.upload_dl_front(imageData);
}, error => {
this.func.showAlert('Error',JSON.stringify(error));
});
}
upload_dl_front(imageFileUri: any): void {
this.file.resolveLocalFilesystemUrl(imageFileUri)
.then(entry => (<FileEntry>entry).file(file => this.readFile_dl_front(file)))
.catch(err => console.log('Error',JSON.stringify(err)));
}
private readFile_dl_front(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const imgBlob = new Blob([reader.result], { type: file.type });
this.dl_front_imageUri = imgBlob;
this.dl_front_imageName = file.name;
alert(this.dl_front_imageName)
const img = new FormData();
img.append('image', this.dl_front_imageUri, this.dl_front_imageName)
this.api.test(img).then(data=>alert("final: "+data))
};
reader.readAsArrayBuffer(file);
}
and my api function is
test(image){
let headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
});
return new Promise( resolve => {
this.http.post(url, image, { headers: headers})
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}
and i am getting the file in my laravel server as
$image = $request->file('image');
but i am getting null in the image parameter.
What am i doing wrong here?
You should remove the headers in the api call.
test(image){
return new Promise( resolve => {
this.http.post(url, image)
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}

Error constructing as per schema

I have the following defined in my server.js,
//server.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var userSchema = new Schema({
"userName": {
type: String,
unique: true
},
"password": String,
"loginHistory": [{
"userAgent": String,
"dateTime": Date
}]
});
var User;
module.exports.initialize = () => {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection("mongodb://<dbuser>:<dbpassword>#ds237409.mlab.com:37409/web322_a6");
db.on('error', (err)=>{
reject(err); // reject the promise with the provided error
});
db.once('open', () => {
User = db.model("users", userSchema);
resolve();
});
})
};
I have a function that is called when posting to my app.post('/register') route, and it basically builds a new User, then assigns it to the passed data, and resolves it afterwards.
module.exports.registerUser = (userData) => {
return new Promise((resolve, reject) => {
if (userData.password != userData.password2) {
reject("Passwords do not match!");
}
let newUser = new User(userData);//<!-- 'Error: TypeError: User is not a constructor'
newUser.save((err) => {
if(err.code == 11000) {
reject("Username already taken");
} else {
reject("Error creating User: " + err);
}
// exit the program after saving
//process.exit();
resolve();
});
})
}
At first I thought I've misdefined User, but I seem to have initialized it properly, as per the MongoDB documentation. Any thoughts? It keeps throwing Error: TypeError: User is not a constructor
EDIT: /post / register
app.post("/register", (req, res) => {
console.log("entering1");
dataServiceAuth.registerUser(req.body).then((data) => {
res.render('register', {successMessage: "User Created"});
}).catch((err) => {
console.log("Error: " + err);
res.render('register', {errorMessage: err, userName: req.body.userName});
})
});
My error was in,
let db = mongoose.createConnection("mongodb://<dbuser>:<dbpassword>#ds237409.mlab.com:37409/web322_a6");
The greater than and less than signs are not to be used. Proper string:
let db = mongoose.createConnection("mongodb://dbuser:dbpassword#ds237409.mlab.com:37409/web322_a6");