Dart shelf router routes not being reached - api

I have written a simple backend RESTAPI web app. I can get the vehicles routes to work but not if i try to reach these routes: File: web/Network/service.dart line 22
app.get('/vehicles/<id|.*>', (Request request, String id) {
or even something simple like this: File: web/Network/service.dart line 17
app.get('/hi/<name|.*>', (Request request, String name) async {
the / and /vehicles work. I have the code on github:
https://github.com/hassandaru/dart_middleware_example/blob/main/web/Network/service.dart
The issue bits are:
app.get('/hi/<name|.*>', (Request request, String name) async {
return await Response.ok('hello $name',headers: {'Content-Type': 'application/json' });
});
app.get('/vehicles/<id|.*>', (Request request, String id) {
final parseId = id.isNotEmpty ? id.toString() : '0';
var result = APICalls().fetchByID(parseId);
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
It matches everything in the documentation. Any suggestions would be greatly appreciated.
import '../dbsettings.dart' as db;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'dart:convert';
import 'apiCall.dart';
class Service {
Handler get handler {
var app = Router();
app.get('/', (Request request) {
return Response.ok('hello transport API', headers: {'Content-Type': 'application/json'});
});
app.get('/hi/<name|.*>', (Request request, String name) async {
return await Response.ok('hello $name',headers: {'Content-Type': 'application/json' });
});
app.get('/vehicles/<id|.*>', (Request request, String id) {
final parseId = id.isNotEmpty ? id.toString() : '0';
var result = APICalls().fetchByID(parseId);
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
//to read all entries of vehicle
app.get('/vehicles', (Request request) async {
var result = await APICalls().showAllVehicles();
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
return app;
}
}

Related

Is there any way to catch the response data which is causing the POST 400 (Bad Request) for Vue js fetch api?

I am sending post request from an array by looping through all indexes one by one.
function apiService(endpoint, method, data) {
// D.R.Y. code to make HTTP requests to the REST API backend using fetch
const config = {
method: method || "GET",
body: data !== undefined ? JSON.stringify(data) : null,
headers: {
'content-type': 'application/json',
'X-CSRFTOKEN': CSRF_TOKEN
}
};
return fetch(endpoint, config)
.then(handleResponse)
.catch(error => console.log(error))
}
let len = this.rowObject.length;
for (var i = 0; i <len; i++) {
apiService(endpoint, method, this.rowObject[i]);
}
I want to catch the this.rowObject[i] object or the i index which causes bad 400 request.
Can it be done using try catch?
You can inject an error handler that captures the information you want, like with onError below.
function apiService(endpoint, method, data, onError) {
// D.R.Y. code to make HTTP requests to the REST API backend using fetch
const config = {
method: method || "GET",
body: data !== undefined ? JSON.stringify(data) : null,
headers: {
'content-type': 'application/json',
'X-CSRFTOKEN': CSRF_TOKEN
}
};
return fetch(endpoint, config)
.then(handleResponse)
.catch(onError)
}
let len = this.rowObject.length;
for (var i = 0; i <len; i++) {
let onError = error => console.log("Error on rowObject " + i + ": " + error);
apiService(endpoint, method, this.rowObject[i], onError);
}

redirecting get request to post request? using express

Is that possible to redirect from Get request to POST request using Express JS? I'm just redirecting from API merchant a get request and need to throw a data back that's why i need to use POST request to send it back.
router.get('/webhooks/success',(req, res) => {
res.redirect(307, '/webhooks/success')
})
router.post('/webhooks/success', async function(req, res){
try{
var request = require('request');
var buffer = Buffer.from('pk-7xvHjw43SOGNLpot677GfxoLasdasdaa44TOJkREVMo')
var base = buffer.toString('base64');
let auth = 'Basic ' + base
var options = {
'method': 'POST',
'url': 'url',
'headers': {
'Content-Type': 'application/json',
'Authorization': JSON.stringify(auth)
},
body: JSON.stringify({
......
})
};
// req.setHeader(options)
request(options, async function (error, response) {
if (response === null || response === undefined || error) throw createError(403, error)
console.log('RESPONSEE', response)
if (response.statusCode === 200) return res.redirect('/success');
throw createError(500, error)
});
}catch(e){
error_logs(e, req)
req.flash('error', e.message)
res.redirect('back')
}
});
I Just ended up by using another api post request
router.get('/webhooks/success',async (req, res) => {
try{
var request = require('request');
var options = {
'method': 'POST',
'url': 'url',
'headers': {
'Content-Type': 'application/json',
}
}
request(options, async function (error, response) {
if (response === null || response === undefined || error) throw createError(403, error)
if (response.statusCode === 200) return res.redirect('/success');
res.redirect('/buy_ticket')
});
}catch(e){
error_logs(e, req)
req.flash('error', e.message)
res.redirect('/buy_ticket')
}
})

In Nodejs/Express js i am unable to return response to Angular 6

I am using Angular 6 and Nodejs/Expressjs to avoid cross domain issue. So here is my code
In Angular i am calling:
this.httpClient.post('/uploadFile', formData, {params: params})
.pipe(map((res: any) => {return res}),
catchError((error: HttpErrorResponse) => {})
Nodejs/Expressjs:
app.post('/uploadFile', (req, res) => {
let formData
const form = new IncomingForm();
let readStream;
form.on('file', (field, file) => {
console.log('file.path>>>',file.path);
readStream = fs.createReadStream(file.path);
});
form.on ('fileBegin', function(name, file) {
//rename the incoming file to the file's name
let fileName = file.path.split("\\");
fileName[fileName.length-1] = file.name.split('.')[0];
fileName = fileName.join("\\");
file.path = fileName;
console.log('file.path', file.path);
console.log('file.name', file.name);
})
form.parse(req, function (err, fields, files) {
formData = new FormData();
formData.append("file", readStream);
formData.append('package_name', req.query.packagename);
formData.append('type', req.query.type);
formData.append('version', req.query.version);
formData.append('descr', req.query.descr);
console.log('req.query.packagename',req.query.packagename);
const axiosConfig = {
headers: {
'Content-Type': 'multipart/form-data'
}
};
let uploadRequest = request.post("WebAPiCallURL", requestCallback);
uploadRequest._form = formData;
uploadRequest.setHeader('Content-Type', 'multipart/form-data');
function requestCallback(err, res, body) {
return JSON.parse(body);
}
});
});
From requestCallback i am unable to send response to Angular6
Your not sending response from to the client. To send you can use res.send or any of the response function from Expressjs.
function requestCallback(err, response, body) { //Rename res to response to avoid conflict
res.send(body); // Send Response to Client
}
Note : As you used same variable res for request, Rename to some other name

Api call is not happening while calling Http Request using HttpClient in angular 7

I am converting a post API request written in javascript to typescript, but my new code seems to be not running as i do not see any network calls in the debugger. Please find my code snippets below.
javascript (working)
private resourcesAccessable(url, token, clientId, resources) {
var request = new XMLHttpRequest();
request.open('POST', url, false);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
console.log(request);
var response ;
request.onreadystatechange = function () {
if (request.readyState == 4) {
var status = request.status;
if (status >= 200 && status < 300) {
response = JSON.parse(request.responseText);
} else if (status == 403) {
console.log('Authorization request was denied by the server.');
return null;
} else {
console.log('Could not obtain authorization data from server.');
return null;
}
}
}
var params = "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&response_mode=permissions&audience="+clientId;
if(Array.isArray(resources)){
for (var i = 0; i < resources.length; i++) {
params = params+"&permission="+resources[i]
}
}
request.send(params);
console.log(response);
return response;
}
typescript (not working)
resourcesAccessable(url, token, clientId, resources) {
private http: HttpClient,
private payload
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
})
};
this.payload = new URLSearchParams();
this.payload.set('grant_type','urn:ietf:params:oauth:grant-type:uma-ticket');
this.payload.set('response_mode','permissions');
this.payload.set('audience', clientId);
this.payload.set('permission',resources);
return this.http.post(url, payload.toString(), httpOptions)
.pipe(
tap(
(data) => {
console.log('----->>>', data);
}
)
), error => {
console.log('error ' + JSON.stringify(error));
};
}
I have tried many things to run the above code but none of them worked for me.
Split your code into the following sections. Angular/RxJS is different from vanilla JavaScript. You create Observable http calls which the Subscriber then reads from.
Inject HttpClient into your class -- necessary for http calls to work. (Needs additional dependencies to work. Please refer https://angular.io/guide/http)
constructor(protected http: HttpClient) {}
Function Definition
resourcesAccessable(url, token, clientId, resources): Observable<any> {
const payload = new URLSearchParams()
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
})
}
payload.set('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket')
payload.set('response_mode', 'permissions')
payload.set('audience', clientId)
payload.set('permission', resources)
return this.http.post(url, payload.toString(), httpOptions)
}
Function Call
this.resourcesAccessable('', '', '', '')
.subscribe(
(data) => {
console.log('----->>>', data);
}
, error => {
console.log('error ' + JSON.stringify(error));
},
() => console.log('Completed'));

Request Header not being sent as a parameter to API calls

I was trying to make an API call to another domain, which has no-cors enabled.
The API call was made something like this:
let url = `https:sampleApiUrl?params=xxxx`;
console.log("hitting dashboard url")
get(url, token)
.then((resp) => {
console.log("resp", resp)
})
.catch((error) => {
console.log(error)
})
This API call, subsequently calls a 'get' method:
const get = (url, authToken) => {
return baseFetch(url, 'get', false, authToken).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
});
}
Now, this get method calls a baseFetch method:
const baseFetch = (url, verb, body, authToken) => {
const request = {
method: verb,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'credentials': 'include'
},
mode: 'cors'
}
if (authToken){
// adding x-access-token in the request header
request.headers['x-access-token'] = authToken;
}
if (body){
request.body = JSON.stringify(body);
}
return fetch(url, request);
}
Now, when this API call is requested, I can't see the "x-access-token" populated in the browser network call.
No x-access-token in request-headers
Also, I am not sure why I get status code 204 in response.
Calling this API from postman and directly from browser or calling as a curl request, returns the correct response.
Thanks
Looking at the image, you are looking at the headers for pre flight OPTIONS method and not the GET method. The pre flght request is generated by the browser and it never has any custom header. therefore it did not have the x-access-token in its headers.