I am new to suitescript, I have been trying to generate a passwordGuid but it gives me a plain text and I expected something encrypted.
I have configured a digital ocean droplet as a SFTP client.
Generated the private and public key
I am using this code provided by one of the guys but I always don't get the expected password Guid
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define([
'N/ui/serverWidget',
'N/https',
'N/log',
'N/url'
],
function (
ui,
https,
log,
url
) {
var HOST_KEY_TOOL_URL = 'https://ursuscode.com/tools/sshkeyscan.php?url=';
function getFormTemplate() {
var form;
form = ui.createForm({
title: 'Password Form'
});
form.addSubmitButton({
label: 'Submit'
});
return form;
}
function addSelectorFields(form) {
var select = form.addField({
id: 'selectaction',
type: ui.FieldType.SELECT,
label: 'Select Action'
});
select.addSelectOption({
value: 'getpasswordguid',
text: 'Get Password GUID'
});
select.addSelectOption({
value: 'gethostkey',
text: 'Get Host Key'
});
return form;
}
function addPasswordGUID1Fields(form) {
var frm = form;
frm.addField({
id: 'restricttoscriptids',
type: ui.FieldType.TEXT,
label: 'Restrict To Script Ids'
}).isMandatory = true;
frm.addField({
id: 'restricttodomains',
type: ui.FieldType.TEXT,
label: 'Restrict To Domains'
}).isMandatory = true;
return frm;
}
function addPasswordGUID2Fields(form, restrictToScriptIds, restrictToDomains) {
form.addCredentialField({
id: 'password',
label: 'Password',
restrictToScriptIds: restrictToScriptIds.replace(' ', '').split(','),
restrictToDomains: restrictToDomains.replace(' ', '').split(',')
});
return form;
}
function addHostKeyFields(form) {
form.addField({
id: 'url',
type: ui.FieldType.TEXT,
label: 'URL (Required)'
});
form.addField({
id: 'port',
type: ui.FieldType.INTEGER,
label: 'Port (Optional)'
});
form.addField({
id: 'hostkeytype',
type: ui.FieldType.TEXT,
label: 'Type (Optional)'
});
return form;
}
function onRequest(option) {
var method;
var form;
var selectAction;
var port;
var hostKeyType;
var restricttoscriptids;
var restricttodomains;
var password;
var theResponse;
var myUrl;
var url;
method = option.request.method;
form = getFormTemplate(method);
if (method === 'GET') {
form = addSelectorFields(form);
}
if (method === 'POST') {
selectAction = option.request.parameters.selectaction;
if (selectAction === 'getpasswordguid') {
form = addPasswordGUID1Fields(form);
} else if (selectAction === 'gethostkey') {
form = addHostKeyFields(form);
} else {
password = option.request.parameters.password;
log.debug("password",password)
log.debug("URL",url)
log.debug("port",port)
log.debug("hostKeyType",hostKeyType)
log.debug("restricttoscriptids",restricttoscriptids)
log.debug("restricttodomains",restricttodomains)
url = option.request.parameters.url;
port = option.request.parameters.port;
hostKeyType = option.request.parameters.hostkeytype;
restricttoscriptids = option.request.parameters.restricttoscriptids;
restricttodomains = option.request.parameters.restricttodomains;
if (restricttoscriptids && restricttodomains) {
form = addPasswordGUID2Fields(form, restricttoscriptids, restricttodomains);
}
if (password) {
form.addField({
id: 'passwordguidresponse',
type: ui.FieldType.LONGTEXT,
label: 'PasswordGUID Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = password;
}
if (url) {
myUrl = HOST_KEY_TOOL_URL + url + '&port=' + port + '&type=' + hostKeyType;
theResponse = https.get({ url: myUrl }).body;
form.addField({
id: 'hostkeyresponse',
type: ui.FieldType.LONGTEXT,
label: 'Host Key Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = theResponse;
}
}
}
option.response.writePage(form);
}
return {
onRequest: onRequest
};
});
Related
here i have two scripts one is suitelet other one is client script .
Please forgive me for the silly mistake as I have not much knowledge in netsuite.
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/record','N/ui/serverWidget','N/redirect','N/runtime','N/search'],function(record,serverWidget,redirect,runtime,search){
function onRequest(context){
var Request = context.request;
var Response = context.response;
if(Request.method == 'GET') {
var form=serverWidget.createForm({title:"Customer entry Suitelet"});
var primaryinfo=form.addFieldGroup({
label:'Primary Information',
id:'custpage_advs_primary_info',
});
var firstname=form.addField({
label:'First Name',
id:'custpage_advs_first_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
firstname.isMandatory=true;
var lastname=form.addField({
label:'Last Name',
id:'custpage_advs_last_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
lastname.isMandatory=true;
var email=form.addField({
label:'Email',
id:'custpage_advs_email',
type:serverWidget.FieldType.EMAIL,
container:'custpage_advs_primary_info'
});
email.isMandatory=true;
var phone=form.addField({
label:'Phone',
id:'custpage_advs_phone',
type:serverWidget.FieldType.PHONE,
container:'custpage_advs_primary_info'
});
var mysublist = form.addSublist({
id: 'custpage_advs_sublistid',
type: serverWidget.SublistType.LIST,
label:'My Sublist'
});
mysublist.addField({
id: 'custpage_advs_sublist_internalid',
type: serverWidget.FieldType.INTEGER,
label: 'Internal Id'
});
mysublist.addField({
id: 'custpage_advs_sublist_fullname',
type: serverWidget.FieldType.TEXT,
label: 'Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_fname',
type: serverWidget.FieldType.TEXT,
label: 'First Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_lname',
type: serverWidget.FieldType.TEXT,
label: 'Last Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_email',
type: serverWidget.FieldType.EMAIL,
label: 'Email'
});
mysublist.addField({
id: 'custpage_advs_sublist_phone',
type: serverWidget.FieldType.PHONE,
label: 'Phone'
});
mysublist.addField({
id: 'custpage_advs_sublist_view',
type: serverWidget.FieldType.URL,
label: 'VIEW'
});
var submit=form.addSubmitButton({
id : 'custpage_advs_submit_record',
label : 'Submit'
});
Response.writePage(form);
// form.clientScriptModulePath = './advs_cs_populatesublisttask.js';
form.clientScriptFileId = 91370;
var fnameValue = Request.parameters.custparam_first_name;
var lnameValue = Request.parameters.custparam_last_name;
var emailValue = Request.parameters.custparam_email;
var phoneValue = Request.parameters.custparam_phone;
log.debug("param from clientScript "+fnameValue);
if(fnameValue){
firstname.defaultValue =fnameValue;
// form.clientScriptFileId = 91370;
var fnameValue = Request.parameters.custparam_first_name;
var lnameValue = Request.parameters.custparam_last_name;
var emailValue = Request.parameters.custparam_email;
var phoneValue = Request.parameters.custparam_phone;
var fnamecustomerSearch = search.create({
type:'customrecord_advs_customer_entry_form',
filters:['custrecord_advs_first_name',"startswith",fnameValue],
columns:[
search.createColumn({name: "name"}),
search.createColumn({name: "custrecord_advs_first_name"}),
search.createColumn({name: "custrecord_advs_last_name"}),
search.createColumn({name: "custrecord_advs_email"}),
search.createColumn({name: "custrecord_advs_phone"}),
search.createColumn({name: "internalid"}),
search.createColumn({name: "id"})
]
});
var counter = 0;
fnamecustomerSearch.run().each(function(result) {
log.debug("my result", +result);
var oldfullname = result.getValue('name');
var InternalidVal = result.getValue('internalid');
var firstname=result.getValue('custrecord_advs_first_name');
var lastname=result.getValue('custrecord_advs_last_name');
var email=result.getValue('custrecord_advs_email');
var phone=result.getValue('custrecord_advs_phone');
// var view=result.getValue('view');
var view= result.getValue('edit|view');
log.debug("view is"+view);
mysublist.setSublistValue({
id: 'custpage_advs_sublist_internalid',
line: counter,
value: InternalidVal
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fullname',
line: counter,
value:oldfullname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fname',
line: counter,
value: firstname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_lname',
line: counter,
value: lastname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_email',
line: counter,
value: email
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_phone',
line: counter,
value:phone
});
counter++;
return true;
});
}
}
return true;
}
else
{
var Fname= Request.parameters.custpage_advs_first_name;
var Lname=Request.parameters.custpage_advs_last_name;
var Email=Request.parameters.custpage_advs_email;
var Phone=Request.parameters.custpage_advs_phone;
var Fullname=Fname+' '+Lname;
var customRecord=record.create({
type:'customrecord_advs_customer_entry_form',
isDynamic:true,
});
customRecord.setValue({
fieldId:'name',
value:Fullname
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Fname
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Lname
});
customRecord.setValue({
fieldId:'custrecord_advs_email',
value:Email
});
customRecord.setValue({
fieldId:'custrecord_advs_phone',
value:Phone
});
var recordId=customRecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
redirect.toSuitelet({
scriptId: 'customscript_advs_ss_customersuitelet',
deploymentId: 'customdeploy_advs_ss_customersuitelet',
});
}
}
return{
onRequest:onRequest
}
});
and then I added some conditions in client scripts .
but all I need is to add an edit/ view column in my suitelet
FYR
here is my client script
/**
* #NApiVersion 2.0
* #NScriptType ClientScript
*/
define(['N/currentRecord','N/search','N/record','N/url'],function(currentRecord,search,record,url){
function fieldChanged(context) {
var recordObj=context.currentRecord;
var name = context.fieldId;
if (name == 'custpage_advs_first_name'){
var fnameValue=recordObj.getValue({
fieldId:'custpage_advs_first_name'
});
alert("First name that you have entered is " +fnameValue);
var suiteUrl = url.resolveScript({
scriptId: 'customscript_advs_ss_populatesublisttask',
deploymentId: 'customdeploy_advs_ss_populatesublisttask',
returnExternalUrl:false,
params : {
custparam_first_name : fnameValue, //define a parameter and pass the value to it
}
});
}
}
else{
return true;
}
setWindowChanged(window,false);
window.location = suiteUrl;
}
return{
fieldChanged:fieldChanged
}
});
I guess I'm mostly just looking for a high level answer, because I'm not sure I'm even approaching this correctly.
You should reduce the code you paste in your question to the parts that isolate the problem.
To solve your issue, add a new field of type INLINEHTML.
sublist.addField({
id: 'YOUR_ID',
label: 'YOUR_LABEL',
type: serverWidget.FieldType.INLINEHTML
})
For each line, set the value to a link using regular html anchor tags.
const view_url = url.resolveRecord({
recordType: TYPE
recordId: ID,
isEditMode: false
})
const edit_url = url.resolveRecord({
recordType: TYPE
recordId: ID,
isEditMode: true
})
sublist.setSublistValue({
line: LINE,
id: 'YOUR_ID',
value: `view / edit`
})
I am using Angular as frontend and NodeJS for the backend.
I have a route that saves the data received from the frontend to the database. When I execute the save() method, I get prompted the following error:
err : ValidationError: conf.0: Cast to [Boolean] failed for value "[ {
name: 'v', percentage: 2, type: false, status: true } ]" (type string)
at path "conf.0"
Below is the route that stores the data:
app.post("/api/submitTaxCollection", (req, res) => {
console.log(req.body);
const submitTaxSchema = new addTaxesSchema(req.body);
try {
submitTaxSchema.save(function (err) {
if (err) return console.log("err : " + err);
});
} catch (error) {
console.log("ERROR : " + error);
return res.send(error);
}
});
and this is the schema.ts file:
var mongoose = require("mongoose");
//Define a schema
var taxSchema = mongoose.Schema;
var AddTaxSchema = new taxSchema({
parentId: String,
conf: [
{
name: String,
percentage: Number,
type: Boolean,
status: Boolean,
},
],
});
var newTaxesSchema = mongoose.model("addTaxSchema", AddTaxSchema);
module.exports = newTaxesSchema;
In Angular, model is setup as below:
export class TaxRatesConfigurationsModel {
name: string = "";
percentage: number = 0;
type: boolean = false;
status: boolean = true;
}
export class TaxRatesModel {
parentId: string = "";
conf: TaxRatesConfigurationsModel[] = [];
}
and I am calling the API as below:
this._httpService
.post(environment.url + "/api/submitTaxCollection", request)
.subscribe((data) => {
console.log(data);
});
when I console.log(req.body);, I get the following printed to the console (Nodejs):
{
parentId: '23948923nur8cw9yicnyu',
conf: [ { name: 'v', percentage: 2, type: false, status: true } ]
}
and the error occurs in Nodejs
What is causing this weird issue?
when i try to upload image on heroku i get this error :
Mixed Content: The page at 'https://twassol.herokuapp.com/' was loaded over HTTPS, but requested an insecure image 'http://twassol.herokuapp.com/images/%D8%A8%D8%B7%D8%A7%D8%B1%D9%8A%D9%82-1564103914328.jpg'. This content should also be served over HTTPS.
and this error:
cross-Origin Read Blocking (CORB) blocked cross-origin response http://twassol.herokuapp.com/images/%D8%A8%D8%B7%D8%A7%D8%B1%D9%8A%D9%82-1564103914328.jpg with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
i tried to use "http://twassol.herokuapp.com/" , it upload the image but does't show it.
this's post.service.ts file :
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { Post } from './post.model';
import { environment } from '../../environments/environment';
const BACKEND_URL = environment.apiUrl + '/posts/';
#Injectable({providedIn: 'root'})
export class PostsService {
private posts: Post[] = [];
private postsUpdated = new Subject<{posts: Post[], postsCount: number}>();
constructor(private http: HttpClient, private router: Router){}
getPosts(postsPerPage: number, currentPage: number) {
const queryParams = `?pagesize=${postsPerPage}&page=${currentPage}`
this.http.get<{ message: string, posts: any, maxPosts: number }>(BACKEND_URL + queryParams)
.pipe(map( postData => {
return { posts :postData.posts.map(post =>{
return{
title: post.title,
content: post.content,
id: post._id,
imagePath: post.imagePath,
creator: post.creator
}
}), maxPosts: postData.maxPosts};
}))
.subscribe((transformedPostData) => {
this.posts = transformedPostData.posts;
this.postsUpdated.next({posts: [...this.posts], postsCount: transformedPostData.maxPosts});
});
}
getPostUpdateListener(){
return this.postsUpdated.asObservable()
}
getPost(id: string){
return this.http.get<{_id: string, title: string, content: string, imagePath: string, creator: string}>(
BACKEND_URL + id
);
}
addPost(title: string, content: string, image: File){
const postData = new FormData;
postData.append('title', title);
postData.append('content', content);
postData.append('image', image, title);
this.http.post<{message: string, post: Post}>(BACKEND_URL, postData)
.subscribe( responseData => {
this.router.navigate(['/']);
});
}
updatePost(id: string, title: string, content: string, image: string | File){
let postData: Post | FormData;
if (typeof(image) === 'object'){
postData = new FormData;
postData.append('id', id);
postData.append('title', title);
postData.append('content', content);
postData.append('image', image, title);
} else {
postData = {
id: id,
title: title,
content: content,
imagePath: image,
creator: null
}
}
this.http
.put(BACKEND_URL + id, postData)
.subscribe(response => {
this.router.navigate(['/']);
});
}
deletePost(postId: string){
return this.http.delete(BACKEND_URL + postId)
}
}
convert your image in to base64 string and pass it in the post request
html:
<button type="button" (click)="upload.click()" >
<span>Upload Photo</span>
</button>
<input #upload formControlName="imageData" type="file" name="imageData" accept='image/*' (change)="getFiles($event)"style="display:none;">
ts:
getFiles(event) {
this.files = event.target.files;
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(this.files[0]);
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64DataOfImage= btoa(binaryString);
this.{{your Model}}.imageData = this.base64DataOfImage
this.fileSrc = 'data:image/png;base64,'+this.base64DataOfImage;
}
retriving data back from service
html
<img height="200" [src]="fileSrc" />
ts
//service call(assuming the returned as {"imageData":"base64data"})
this.fileSrc='data:image/png;base64,'+responce.imageData;
make sure you increse your request body size in backend
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
I'm trying to learn the basics of fhir and want to implement in node js.
I have come across the following code https://github.com/FHIR/fhir.js
In that it says that i have to create a instance of FHIR client?
I know my question is dumb, so can i get any clarifications on the topic.
I have started learning node a few days back.
Thanks in advance!
var config = {
// FHIR server base url
baseUrl: 'http://myfhirserver.com',
auth: {
bearer: 'token',
// OR for basic auth
user: 'user',
pass: 'secret'
},
// Valid Options are 'same-origin', 'include'
credentials: 'same-origin',
headers: {
'X-Custom-Header': 'Custom Value',
'X-Another-Custom': 'Another Value',
}
}
myClient = fhir(config, adapter)
Above is the code for creating an instance of Fhir client, I want to know where should i implement this code and access a fhir server.
From the README, for use with Node:
var mkFhir = require('fhir.js');
var client = mkFhir({
baseUrl: 'http://try-fhirplace.hospital-systems.com'
});
client
.search( {type: 'Patient', query: { 'birthdate': '1974' }})
.then(function(res){
var bundle = res.data;
var count = (bundle.entry && bundle.entry.length) || 0;
console.log("# Patients born in 1974: ", count);
})
.catch(function(res){
// Error responses
if (res.status){
console.log('Error', res.status);
}
// Errors
if (res.message){
console.log('Error', res.message);
}
});
I would recommend using one of the publicly available FHIR test servers as outlined here: http://wiki.hl7.org/index.php?title=Publicly_Available_FHIR_Servers_for_testing
It seems as though you are generating a client for communicating with the FHIR server but you would need to update the base URL in the third line of your code.
FHIR WITH NODEJS
First we need to fetch the access Token
After fetching the token we can easily create the Patient record just by passing the values via POSTMAN as req.body and than it will manipulate the request data into FHIR.
We can fetch the Patient record as per our response body.
All three services are coded below:
const CLIENT_ID = FHIR_CLIENT_ID;
const APP_SECRET = FHIR_CLIENT_SECRET;
const { BASE, RESOURCE } = fhir;
const instance = axios.create({
baseURL: RESOURCE,
});
const getAccessToken = async () => {
const response = await axios({
url: `${BASE}/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/oauth2/token`,
method: 'post',
data: `grant_type=Client_Credentials&resource=${RESOURCE}`,
auth: {
username: CLIENT_ID,
password: APP_SECRET,
},
});
return response.data.access_token;
};
const createPatient = async (patientBody) => {
const {
firstName,
middleIniital,
lastName,
birthDate,
gender,
reference,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
} = patientBody;
const newFhirPatient = {
resourceType: 'Patient',
name: [
{ text: 'First Name', given: [firstName] },
{ text: 'Middle Name', given: [middleIniital] },
{ text: 'Last Name', given: [lastName] },
],
birthDate,
gender,
managingOrganization: { type: 'Organization', reference },
address: [{ text: address, city, state, postalCode: zipcode }],
contact: [
{
telecom: [
{ system: 'email', value: email },
{ system: 'phone', value: phone },
],
relationship: {
coding: [
{ display: 'SSN', code: ssn },
{ display: 'MRN', code: mrn },
],
},
},
],
};
const accessToken = await getAccessToken();
try {
const response = await instance.post('/Patient', newFhirPatient, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
throw error;
}
};
const getPatient = async () => {
const accessToken = await getAccessToken();
try {
const response = await instance.get('/Patient', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const data = [];
for (let i = 0; i < response.data.entry.length; i++) {
const entry = response.data.entry[i];
var id = (entry.resource.id !== undefined) ? entry.resource.id : "";
var firstName = (entry.resource.name?.[0]?.given?.[0] !== undefined) ? entry.resource.name?.[0]?.given?.[0] : "";
var middleName = (entry.resource.name?.[1]?.given?.[0] !== undefined) ? entry.resource.name?.[1]?.given?.[0] : "";
var lastName = (entry.resource.name?.[2]?.given?.[0] !== undefined) ? entry.resource.name?.[2]?.given?.[0] : "";
var birthDate = (entry.resource.birthDate !== undefined) ? entry.resource.birthDate : "";
var gender = (entry.resource.gender !== undefined) ? entry.resource.gender : "";
var address = (entry.resource.address?.[0]?.text !== undefined) ? entry.resource.address?.[0]?.text : "";
var city = (entry.resource.address?.[0]?.city !== undefined) ? entry.resource.address?.[0]?.city : "";
var state = (entry.resource.address?.[0]?.state !== undefined) ? entry.resource.address?.[0]?.state : "";
var zipcode = (entry.resource.address?.[0]?.zipcode !== undefined) ? entry.resource.address?.[0]?.zipcode : "";
var ssn = (entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[0].code !== undefined) ? entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[0].code : "";
var mrn = (entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[1].code !== undefined) ? entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[1].code : "";
var email = (entry.resource.contact?.[0]?.telecom?.[0]?.value !== undefined) ? entry.resource.contact?.[0]?.telecom?.[0]?.value : "";
var phone = (entry.resource.contact?.[0]?.telecom?.[1]?.value !== undefined) ? entry.resource.contact?.[0]?.telecom?.[1]?.value : "";
var organizationId = (entry.resource.managingOrganization?.reference !== undefined) ? entry.resource.managingOrganization?.reference : "";
data.push({
id,
firstName,
middleName,
lastName,
birthDate,
gender,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
organizationId,
});
}
return data;
} catch (error) {
throw error;
}
};
After getting the access Token you can create the Patient like this in NodeJS
and send the data into FHIR in their manner
const createPatient = async (patientBody) => {
const {
firstName,
middleIniital,
lastName,
birthDate,
gender,
reference,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
} = patientBody;
const newFhirPatient = {
resourceType: 'Patient',
name: [
{ text: 'First Name', given: [firstName] },
{ text: 'Middle Name', given: [middleIniital] },
{ text: 'Last Name', given: [lastName] },
],
birthDate,
gender,
managingOrganization: { type: 'Organization', reference },
address: [{ text: address, city, state, postalCode: zipcode }],
contact: [
{
telecom: [
{ system: 'email', value: email },
{ system: 'phone', value: phone },
],
relationship: {
coding: [
{ display: 'SSN', code: ssn },
{ display: 'MRN', code: mrn },
],
},
},
],
};
const accessToken = await getAccessToken();
try {
const response = await instance.post('/Patient', newFhirPatient, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
throw error;
}
};
I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.