On the button click event of React side I am calling a node backend.
click event of react,
// calling node backend
this.uploadApi.command(postData.bin_files, this.dummy);
this.setState({submit_form});
}
dummy = (result)=>{
console.log(result);
}
This is my Node backend code,
import axios from 'axios';
class UploadFile {
constructor() {
this.url = 'http://localhost:56246/microservice/uploaddata'; //This is the local MVC application's URL (microservice is the controller)
}
command(postData, callback, uploadCallback = null) {
let jsonDataString = JSON.stringify(postData).replace(/&/g, '--and--');
jsonDataString = jsonDataString.replace(/\+/g, '--plus--');
const payload = JSON.parse(jsonDataString);
console.log('----------');
console.log(this.url);
console.log(payload);
console.log('----------');
// var data = qs.stringify({'jsondata':payload});
const data = new FormData();
for (var i = 0; i < payload.length; i++) {
console.log('inside for 1');
data.append(`model[${i}].name`, payload[i].name);
data.append(`model[${i}].bin_file`, payload[i].bin_file);
console.log('inside for 2');
}
console.log('=============');
console.log(data);
console.log('=============');
var config = {
method: 'post',
url: this.url,
headers: {
'Content-Type': 'multipart/form-data'
},
data: "jsondata=" + data,
onUploadProgress: (progressEvent) => {
const {
loaded,
total
} = progressEvent;
console.log("loaded:", loaded);
console.log("total:", total);
if (uploadCallback !== null) uploadCallback(progressEvent);
}
};
axios(config)
.then(function(response) {
// console.log(JSON.stringify(response.data));
callback(response.data);
})
.catch(function(error) {
console.log(error);
});
// axios.post(this.url, data)
// .then(res => console.log(res.data))
// .catch((error) => { console.error(error) });
}
}
export default UploadFile;
And this is my respective controller,
public dynamic UploadData(List<MemberInfo> model)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = mstrDBConStringNew;
conn.Open();
SqlCommand command = new SqlCommand("SELECT * from tempstorage", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//port = reader.GetString(0);
}
}
}
return "Hiiiiiiii";
}
public class MemberInfo
{
public string name { get; set; }
public string bin_file { get; set; }
}
Now If I show You while debugging, the controller and its respective action gets called but the value that I am expecting is null.
I have also tried like this way, but no luck
public dynamic UploadData(FormCollection model)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = mstrDBConStringNew;
conn.Open();
SqlCommand command = new SqlCommand("SELECT * from tempstorage", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//port = reader.GetString(0);
}
}
}
return "Hiiiiiiii";
}
This is my network request,
Please ask if anything additional is needed.
Yes I was able to figure out the issue,
var config = {
method: 'post',
url: this.url,
headers: {
'Content-Type': 'multipart/form-data'
},
data: data, // previously it was, "jsondata=" + data
Here I am getting the data as expected..
Related
Having a very very peculiar issue happening:
When i start my node application, i set my access tokens to an instance of a model like so:
index.js
const token = new Tokens();
token.setTokens(access_token, refresh_token);
console.log(token.getTokens()) // WORKS
I then call the getter functions in my instance in different files.
RunSchedular.js
const tokens = Tokens.getInstance();
console.log('sched',tokens.getTokens()) //WORKS
API.js
export const POSTRequest = () => {
const currentTokens = Tokens.getInstance();
const refreshToken = currentTokens.getRefreshToken(); // DOES NOT WORK
const body = {
method: 'POST',
headers:
{
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
body: qs.stringify({
client_secret: clientSecret,
client_id: clientId,
refresh_token: refreshToken,
grant_type: 'refresh_token',
redirect_uri: redirectUri
})
};
return body;
}
My model is like so:
let instance = null;
export default class Tokens {
constructor() {
if(!instance) {
instance = this;
}
this.accessToken = '';
this.refreshToken = '';
}
getAccessToken() {
return this.accessToken;
}
setAccessToken(value) {
this.accessToken = value;
}
getRefreshToken() {
return this.refreshToken;
}
setRefreshToken(value) {
this.refreshToken = value;
}
getTokens() {
return {
accessToken: this.accessToken,
refreshToken: this.refreshToken
}
}
setTokens(accessToken,refreshToken) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
static getInstance() {
console.log('instance', instance)
if(!instance) {
instance = new Tokens();
}
return instance;
}
};
Any ideas why this could be happening? The instance in the API.js does not return my access tokens (access token = '' as per the constructor) where as the schedular.js and index.js returns my access token fine?
Is my Model not correct?
How are you importing the Tokens module? If the path is different, 2 different modules will be imported.
E.G.:
import { Tokens } from 'src/singletons/Tokens';
Will be a different object than:
import { Tokens } from './../singletons/Tokens';
More information about singletons in javascript.
More information about module caching in NodeJS.
I am trying to pass an object to my NodeJS server from my angular application. I can read the object perfectly fine on the client-side, but not serverside.
Here is my client-side:
var query = {
date: '9-2-2019',
size: 4
}
this.http.get<any>(url, {params: {query: query} }).toPromise();
Why can I not pass this to my Node JS server?
No overload matches this call.
Is my error.
Please change { params: {query: query}} to be {params: query} and also change query.size to be string instead of number
var query = {
date: '9-2-2019',
size: '4'
}
this.http.get<any>(url, {params: query}).toPromise().then(response => {
console.log(response);
})
.catch(console.log);
Alternative
Create // utils.service.ts
import { HttpParams } from '#angular/common/http';
// ...
export class UtilsService {
static buildQueryParams(source: Object): HttpParams {
let target: HttpParams = new HttpParams();
Object.keys(source).forEach((key: string) => {
const value: string | number | boolean | Date = source[key];
if ((typeof value !== 'undefined') && (value !== null)) {
target = target.append(key, value.toString());
}
});
return target;
}
}
then use it in your service
import { UtilsService } from '/path/to/utils.service';
var query = {
date: '9-2-2019',
size: 4
}
const queryParams: HttpParams = UtilsService.buildQueryParams(query);
this.http.get<any>(url, {params: queryParams }).toPromise().then(response => {
console.log(response);
})
.catch(console.log);
I'm trying to build a React app where users can save specific things under their ID.
I'm using nodeJS with React and auth0 for authentication.
I'm trying to access a property on the this.props.auth object and find if that property exists in my db so if there's a match something can be saved under the user's ID.
However I'm not able to access this.props.auth.id as shown in the code below but I can access this.props.auth
Any pointers?
.
.
.
Auth.js
import history from '../../history';
import auth0 from 'auth0-js';
import { AUTH0_CONFIG } from '../../auth0';
import API from "../../utils/API"
export default class Auth {
accessToken;
idToken;
expiresAt;
userProfile;
userImage;
name;
id;
auth0 = new auth0.WebAuth({
domain: AUTH0_CONFIG.domain,
clientID: AUTH0_CONFIG.clientId,
redirectUri: AUTH0_CONFIG.callbackUrl,
responseType: 'token id_token',
scope: 'openid profile'
})
constructor() {
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
this.getAccessToken = this.getAccessToken.bind(this);
this.getIdToken = this.getIdToken.bind(this);
this.renewSession = this.renewSession.bind(this);
this.userInfo = this.userInfo.bind(this)
}
login() {
this.auth0.authorize();
}
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
API.saveUser(authResult.idTokenPayload);
history.replace('/')
} else if (err) {
history.replace('/');
console.log(err);
alert(`Error: ${err.error}. Check the console for further details.`);
}
});
}
getAccessToken() {
return this.accessToken;
}
getIdToken() {
return this.idToken;
}
userInfo() {
return this.userProfile
}
setSession(authResult) {
// Set isLoggedIn flag in localStorage
localStorage.setItem('isLoggedIn', 'true');
console.log(authResult);
let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
this.accessToken = authResult.accessToken
this.idToken = authResult.idToken;
this.expiresAt = expiresAt;
this.userImage = authResult.idTokenPayload.picture;
this.name = authResult.idTokenPayload.name.split(' ', 1);
this.id = authResult.idTokenPayload.nickname;
// navigate to the home route
history.replace('/');
}
renewSession() {
this.auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult)
console.log('authresult', authResult);
} else if (err) {
this.logout();
console.log(err);
alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
}
});
}
logout() {
// Remove tokens and expiry time
this.accessToken = null;
this.idToken = null;
this.expiresAt = 0;
// Remove isLoggedIn flag from localStorage
localStorage.removeItem('isLoggedIn');
// navigate to the home route
history.replace('/');
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = this.expiresAt;
return new Date().getTime() < expiresAt;
}
}
Home.js
class Home extends Component {
constructor(props) {
super(props)
console.log(this.props); // can access this
console.log(this.props.auth.id); // this shows undefined
this.state = {
news: [],
summary:[],
summaryUrl: '',
userID: '',
user: '', //
pageLoading: true,
gistLoading: true
}
// console.log(this.state);
}
goTo(route) {
// console.log(history, route);
this.props.history.replace(`/${route}`)
}
login() {
this.props.auth.login();
}
logout() {
this.props.auth.logout();
}
// API call to display trending news
componentDidMount() {
API.getArticles()
.then(res => {
this.setState({
news: res.data,
pageLoading: false,
// user: this.props.auth.id
})
// console.log(this.state);
});
API.getSavedUsers()
.then((res) => {
console.log();
res.data.forEach((el) => {
console.log(this.props.auth.id); // shows undefined
if(el.name === this.props.auth.id){
this.setState({
userID: el.authID
})
} else {
console.log('notfound');
}
})
console.log(this.state);
})
const { renewSession } = this.props.auth;
if (localStorage.getItem('isLoggedIn') === 'true') {
renewSession();
}
}
I may be wrong but from the snapshot the data-type of auth property is Auth which is an object but if you look at it, match, location etc are all shown as {…} that symbolises its an object and hence we fetch the properties using dot. I would suggest parsing the auth first and then accessing the inner properties as follows:
const auth = JSON.parse(this.props.auth);
console.log(auth.id);
Could you try this for once.
am trying to download pdf file from local folder that structures like
assets/test.pdf.
server.js
app.get('/ePoint', (req,res)=>{
// some dumb code :P
});
demo.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Headers } from '#angular/http';
import {Observable} from 'rxjs';
fileDownload() {
const headers = new HttpHeaders();
headers.append('Accept', 'application/pdf');
this._http.get('http://localhost:3000/ePoint', { headers: headers })
.toPromise()
.then(response => this.saveItToClient(response));
}
private saveItToClient(response: any) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: 'application/pdf' });
saveAs(blob, filename);
}
i dont know where i did mistake. in browser network console. its shows 200 ok. but in normal browser console shows as below attachment
Note: i referred for ts file from here
helps much appreciated
try this...
component.ts
downloadDocument(documentId: string) {
this.downloadDocumentSubscription = this.getService.downloadScannedDocument(documentId).subscribe(
data => {
this.createImageFromBlob(data);
},
error => {
console.log("no image found");
$("#errorModal").modal('show'); //show download err modal
});
}
createImageFromBlob(image: Blob) {
console.log("mylog", image);
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(image, "download." + (image.type.substr(image.type.lastIndexOf('/') + 1)));
else {
var url = window.URL.createObjectURL(image);
window.open(url);
}
}
service.ts
downloadScannedDocument(documentId: string): Observable<any> {
let params = new HttpParams();
if (documentTypeParam == false)
params = params.set('onlyActive', 'false');
let fileResult: Observable<any> = this.http.get(`${this.apiBaseUrl}/${documentId}`, { responseType: "blob", params: params });
return fileResult;
}
I am new in programming and I am trying to connect a Progress database using Progress Developer Studio authentication model (/WEB-INF/oeablSecurity-form-local.xml) with KENDO UI for Angular project. When I am using anonymous authentication everything is working fine, but I couldn't manage to make Form authentication with username and password. This is the code:
/// <reference path="progress/progress.d.ts" />
import { Component, ViewChild, Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
import {
GridComponent,
GridDataResult,
DataStateChangeEvent,
// State
} from '#progress/kendo-angular-grid';
import {
State,
process
} from '#progress/kendo-data-query';
import * as Progress from "./progress/progress";
let progress = Progress.progress;
/* Example service */
#Injectable()
export class CategoriesService extends BehaviorSubject<GridDataResult> {
private tableName: string = 'Client';
private jsdoPromise: Promise<Progress.progress.data.JSDO>;
constructor(private http: Http) {
super(null);
const serviceURI = 'serviceURI';
const catalogURI = 'catalogURI';
let opts: Progress.progress.data.JSDOSessionOptions = {
serviceURI: serviceURI,
};
let session = new progress.data.JSDOSession(opts);
this.jsdoPromise = new Promise( (resolve, reject) => {
session.login("", "").done(function (session: Progress.progress.data.JSDOSession, result: any, info: any) {
console.log("session.login");
session.addCatalog(catalogURI).then(() => {
resolve(new progress.data.JSDO('AdvClients'));
});
})
})
}
public query(state: any): void {
this.fetch(this.tableName, state)
.subscribe(x => super.next(x));
}
private fetch(tableName: string, state: State): Observable<GridDataResult> {
let that = this;
let query = {
skip: state.skip,
top: state.take
};
let promise = new Promise((resolve, reject) => {
this.jsdoPromise.then((jsdo) => {
console.log("jsdoPromise.resolve");
let afterFill = (jsdo: any, success: any, request: any) => {
jsdo.unsubscribe('AfterFill', afterFill, this);
if (success) {
let data = jsdo.getData();
if (query.top) {
let afterInvoke = (jsdo1: any, success1: any, request1: any): void => {
jsdo.unsubscribe('AfterInvoke', 'count', afterInvoke, this);
console.log("promise.resolve 1");
resolve(<GridDataResult>{
data: data,
total: request1.response.numRecs
});
};
jsdo.subscribe('AfterInvoke', 'count', afterInvoke, this);
jsdo.count(query);
} else {
console.log("promise.resolve 2");
resolve(<GridDataResult>{
data: data,
total: data.length
});
}
} else {
reject(new Error('Error while executing query'));
}
};
jsdo.subscribe('AfterFill', afterFill, this);
jsdo.fill(query);
})
});
let result = Observable.fromPromise(promise)
.map((ret: GridDataResult) => (<GridDataResult>{
data: ret.data,
total: ret.total
}));
return result;
}
}
I made it.
const serviceURI = 'http://ctc-server:8810/CtcIdea';
const catalogURI = serviceURI + '/static/CtcIdeaService1.json';
const authenticationModel = progress.data.Session.AUTH_TYPE_FORM;
let opts: Progress.progress.data.JSDOSessionOptions = {
serviceURI: serviceURI,
authenticationModel: authenticationModel
};