Angular 5 http post method not called in nodejs - javascript

I have a nodejs as Backend Service and angular 5 as front end, I want to call a POST method to NodeJS Server, send a Blob File to server.
But that post method is executed, and nothing shown on backend console log.
Here are some code piece:
server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(cors());
//create a cors middleware
app.use(function (req, res, next) {
//set headers to allow cross origin request.
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/decrypt', function (req, res) {
console.log("decrypt called");
return 'data back';
})
And in AngularJS:
database.services.ts:
import { Injectable, Input } from '#angular/core';
import { Http, Response, ResponseContentType } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Observable';
import { saveAs, FileSaver } from 'file-saver/FileSaver';
import { HttpClientModule, HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
#Injectable()
export class DatabaseService {
private API_GET_LIST_FILES = 'http://localhost:3000/files';
private BASE_URL = 'http://localhost:3000/';
private API_GET_FILE = 'http://localhost:3000/download?name=';
constructor(private http: Http) { }
getFile(key: string) {
return this.http.get(this.API_GET_FILE + key, {
responseType: ResponseContentType.Blob
})
.map(res => {
return {
filename: key.split('/').pop(),
data: res.blob()
};
})
.subscribe(res => {
this.decryptFile(res.data);
saveAs(res.data, res.filename);
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.');
})
}
decryptFile(data: any): Observable<any> {
const httpOptions = {
Headers: new HttpHeaders({
'Content-Type': 'application/octet-stream',
'data': data
})
};
console.log(data, typeof data, this.BASE_URL + `decrypt`);
return this.http.post(`http://localhost:3000/decrypt`, httpOptions);
}
}
This getFile function will be called once I click the file download button on page, because in the browser console, it will print out the Blob(564534) {size: 564534, type: "application/octet-stream"} "object" "http://localhost:3000/decrypt"
I want the nodejs Server to take this post method and the Blob (GPG file) object as a parameter, and do something.
But looks like the backend server didn't print out anything.
Please advise how to modify this code, should I use POST or PUT? I want to pass a GPG file to nodeJS server and decrypt it.
Thanks,

decryptFile returns Observable, you must subscribe to it to execute the http call:
this.decryptFile(res.data).subscribe(decrypted => {???});
Edit: Could not resist, a few observations, feel free to ignore:
Why do you get a file from server and then send it back there? Why don't you just decrypt the file during the first API call and return that?
From security point of view... nevermind, I just hope there will be some authorization on the server as you are dealing with PGP files...
You should preferably start using HttpClient from #angular/common/http instead of Http. Good news is you have that imported already.
Depending on the size of the files you might want to consider using http upload instead of POST. Still, see the first point.

Related

Reaction request with axes for Node.js, problem in CORS

I am creating a project where your back-end localhost:3333 is developed in node.js and the front-end in react localhost:3000.
When I go to access the API without any type of token or validation, it works perfectly, however when using token to validate accesses, there are some errors in CORS.
When I click on a button in the "Login" application to access the login, there is still no token, so I can make this request successfully, but in the next ones, where the token is requested, the following error occurs:
>Access to XMLHttpRequest at 'http://localhost:3333/processo' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
>GET http://localhost:3333/cliente net::ERR_FAILED
>Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
My chrome network looks like this
>Request URL: http://localhost:3333/processo
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTk3MTc5MDQ0LCJleHAiOjE1OTc3ODM4NDR9.hsj3D1nMSuuHx-r2SofNH0zMiUKIPKeAun1sjccYi7I
Referer: http://localhost:3000/inicio
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
I've tried two things, the first was to add an extension to the chrome "Moesif Cors" it didn't work, it only works when I don't send Bearer.
And the other was trying to change from https to http. but it also didn't work.
how can i solve this? does this problem happen in my service? how do I configure cors to allow the token?
I will show below how my backend end node.js is configured.
server.js
import app from './app';
app.listen('3333');
app.js
import 'dotenv/config';
import express from 'express';
import path from 'path';
import Youch from 'youch';
import * as Sentry from '#sentry/node';
import 'express-async-errors';
import routes from './routes';
import sentryConfig from './config/sentry';
import './database';
class App {
constructor() {
this.server = express();
Sentry.init(sentryConfig);
this.middlewares();
this.routes();
this.exceptionHandler();
}
middlewares() {
this.server.use(Sentry.Handlers.requestHandler());
this.server.use(express.json());
this.server.use(
'/files',
express.static(path.resolve(__dirname, '..', 'tmp', 'uploads'))
);
}
routes() {
this.server.use(routes);
this.server.use(Sentry.Handlers.errorHandler());
}
exceptionHandler() {
this.server.use(async (err, req, res, next) => {
if (process.env.NODE_ENV === 'development') {
const errors = await new Youch(err, req).toJSON();
return res.status(500).json(errors);
}
return res.status(500).json({ error: 'Internal server error' });
});
}
}
export default new App().server;
now i will show how the call is on the front end where i have an api.js file
api.js
import axios from 'axios';
import { getToken } from "./auth";
const api = axios.create({
baseURL: 'http://localhost:3333',
});
api.interceptors.request.use(async config => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default api;
when I remove the header config, the requests work perfectly.
api.interceptors.request.use(async config => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
[EDIT]
I'm starting to think that the problem is the way I'm sending it from the front end and not from the back end
example of a call to the api
async listAll() {
const result = await api.get(apiService);
const list = result.data || [];
this.setState({ list, listaFiltrada: list });
}
Have you tried adding the cors middleware to Express?
If you try this request from a server or PostMan it would work. But since you are trying to make a request from the browser you need enable cors in your express server.
There are two simple way to achieve it;
Use cors library
var cors = require('cors')
var app = express()
app.use(cors());
or Write custom middleware. Manual solution for your case would be;
import 'dotenv/config';
import express from 'express';
import path from 'path';
import Youch from 'youch';
import * as Sentry from '#sentry/node';
import 'express-async-errors';
import routes from './routes';
import sentryConfig from './config/sentry';
import './database';
class App {
constructor() {
this.server = express();
this.enableCORS();
Sentry.init(sentryConfig);
this.middlewares();
this.routes();
this.exceptionHandler();
}
enableCORS(){
this.server.all('*', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
res.setHeader('Access-Control-Allow-Credentials', 'true');
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
}
middlewares() {
this.server.use(Sentry.Handlers.requestHandler());
this.server.use(express.json());
this.server.use(
'/files',
express.static(path.resolve(__dirname, '..', 'tmp', 'uploads'))
);
}
routes() {
this.server.use(routes);
this.server.use(Sentry.Handlers.errorHandler());
}
exceptionHandler() {
this.server.use(async (err, req, res, next) => {
if (process.env.NODE_ENV === 'development') {
const errors = await new Youch(err, req).toJSON();
return res.status(500).json(errors);
}
return res.status(500).json({ error: 'Internal server error' });
});
}
}
export default new App().server;
If you are using a create-react-app project, try using the the proxy option in package.json
"proxy": "http://localhost:3333"
Then you would replace URLs in the client like so
axios.get('/') // maps to http://localhost:3333
axios.get('/api/anything') // maps to http://localhost:3333/api/anyting
Install this on the nodejs side
https://www.npmjs.com/package/cors
config like this
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})

React.js, Express.js and the dreaded CORS

I'm sorry to be posting yet another question about CORS but I just can't figure this one out.
I have a React app using an Express.js server (running on http://localhost:9001) to upload an image to a Google Cloud storage bucket. I keep getting a CORS error even though the image is uploaded successfully and this is preventing me from getting the image's URL returned. I don't really understand how I can get a CORS error even though the image is uploaded but that's what's happening.
I have configured CORS on the Google Cloud storage bucket as follows:
[
{
"origin": ["http://localhost:3000"],
"responseHeader": "*",
"method": ["POST"],
"maxAgeSeconds": 3600
}
]
When I inspect the CORS error I'm getting I see the following:
The origin is http://localhost:3000, so that's configured correctly and I'm using POST to upload the image so that should be allowed as well.
The function I've written to upload the image is as follows:
function postImage(file) {
const formData = new FormData();
formData.append('file', file);
fetch(`${window.location.protocol}//${window.location.hostname}:9001/uploads`, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
// headers: {
// 'Content-Type': 'multipart/form-data'
// },
body: formData
})
// .then((response) => response.json())
.then((response) => console.log('This is your data:', response.data))
.catch(error => {
console.error('There has been a problem uploading your image', error);
});
}
I've commented out the headers as including them kept throwing up a Multipart: Boundary not found error that I've seen others have an issue with and removing the headers setting hasn't caused any other issues.
I have a helper function on the Express server that uploads the image to the Google Cloud storage bucket:
const uploadImage = (file) => new Promise((resolve, reject) => {
const { originalname, buffer } = file
const blob = bucket.file(originalname.replace(/ /g, "_"))
const filetype = blob.name.split('.').pop()
const filename = `${uuidv4()}.${filetype}`
const blobStream = blob.createWriteStream({
resumable: false
})
blobStream.on('finish', () => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${filename}`
)
resolve(publicUrl)
})
.on('error', () => {
reject(`Unable to upload image, something went wrong`)
})
.end(buffer)
})
Here are the functions on my Express server:
import { typeDefs } from './graphql-schema'
import { ApolloServer } from 'apollo-server-express'
import express from 'express'
import neo4j from 'neo4j-driver'
import { makeAugmentedSchema } from 'neo4j-graphql-js'
import dotenv from 'dotenv'
import { initializeDatabase } from './initialize'
const bodyParser = require('body-parser')
const multer = require('multer')
const uploadImage = require('./helpers/helpers')
dotenv.config()
const app = express()
const schema = makeAugmentedSchema({
typeDefs,
config: {
query: {
exclude: ['RatingCount'],
},
mutation: {
exclude: ['RatingCount'],
},
},
})
const driver = neo4j.driver(
process.env.NEO4J_URI,
neo4j.auth.basic(
process.env.NEO4J_USER,
process.env.NEO4J_PASSWORD
),
{
encrypted: process.env.NEO4J_ENCRYPTED ? 'ENCRYPTION_ON' : 'ENCRYPTION_OFF',
}
)
const init = async (driver) => {
await initializeDatabase(driver)
}
init(driver)
const server = new ApolloServer({
context: { driver, neo4jDatabase: process.env.NEO4J_DATABASE },
schema: schema,
introspection: true,
playground: true,
})
// Specify host, port and path for GraphQL endpoint
const port = process.env.GRAPHQL_SERVER_PORT || 4001
const path = process.env.GRAPHQL_SERVER_PATH || '/graphql'
const host = process.env.GRAPHQL_SERVER_HOST || '0.0.0.0'
// Code for uploading files to Google Cloud
app.use((req, res, next, err) => {
console.error(err.stack)
res.header("Access-Control-Allow-Origin", "*");
res.type('multipart/form-data')
res.status(500).json({
error: err,
message: 'Internal server error!',
})
next()
})
const multerMid = multer({
storage: multer.memoryStorage(),
limits: {
// no larger than 5mb.
fileSize: 5 * 1024 * 1024,
},
})
app.disable('x-powered-by')
app.use(multerMid.single('file'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/uploads', async (req, res, next) => {
try {
const myFile = req.file
const imageUrl = await uploadImage(myFile)
res
.status(200)
.json({
message: "Upload was successful",
data: imageUrl
})
} catch (error) {
next(error)
}
})
server.applyMiddleware({ app, path })
app.listen({ host, port, path }, () => {
console.log(`GraphQL server ready at http://${host}:${port}${path}`)
})
app.listen(9001, () => {
console.log('Node.js -> GCP server now listening for requests!')
})
I've tried a lot of different things to get this working:
I've tried adding http://localhost:9001 to the CORS configuration, as well as other URLs
I've tried opening up all origins with "*" for
I've read through all the documentation [here][3]
I've tried following all the troubleshooting documentation Google has here
I've cleared my browser cache as I've seen that can cause the CORS errors to persist - see another post here
I've tried waiting over night for my Google Cloud CORS configuration to take effect as I've heard the configuration can take a bit of time to propagate
Despite all of this I'm still getting the CORS error but my upload is still working. I just need to clear the error so I can get the returned image URL.
You add cors to Google Cloud storage bucket but you forgot to add it to express server POST function. Or use it as global on your express server.
Try this on your express POST function:
res.header("Access-Control-Allow-Origin", "http://example.com");
Or
res.header("Access-Control-Allow-Origin", "*");
Or even better:
/* Headers */
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

Trouble Deploying Angular/Express App in Heroku frontend cannot hit the API endpoint

Currently in development it works just fine... localhost:4200 for the front-end and localhost:8080 for the back-end
However, I just deployed it and the front-end get displayed, but isn't getting the data from the API because in my app.service.ts I'm doing the following:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'http://localhost:8080/api'
constructor(private http: HttpClient) { }
public getNews() {
return this.http.get(`${this.apiUrl}/countries`)
}
}
As you can see, I'm hardcoding the localhost:8080 and it works fine in development, but when it comes to production Heroku does not assign me the port 8080, it assigns me another one.
That being said... How can I tweak this in order to read the port Heroku gives me?
This is my app.js file
const express = require('express');
const app = express();
const scrapper = require('./backend/scrapper')
// Create link to Angular build directory
var distDir = __dirname + "/dist/covid19";
app.use(express.static(distDir));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
app.use("/api/countries", async (req, res, next) => {
const data = await scrapper.getCountries()
res.status(200).json(data)
})
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`API listening on port ${port}...`);
});
module.exports = app;
As you can see I'm declaring my port to be process.env.PORT || 8080, but this is for the backend... How can achieve this but in my API call in the service.ts file?
You guys pointed me in the right direction, but to be precise:
I noticed that in Angular you get a environments folder with two files 1. environment.ts and environment.prod.ts.
I just had to make sure to use to point to the URL that Heroku gave me for my app after deploying yourappname.herokuapp.com, by doing the following in my environments.prod.ts (Which is the one that Heroku is gonna look for)
export const environment = {
production: true,
apiUrl: "https://yourappname.herokuapp.com/api"
};
And in my api.service.ts I ended up with the following code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { environment } from '../environments/environment'
const API_URL = environment.apiUrl;
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
public getNews() {
return this.http.get(API_URL + '/countries')
}
}
When you deploy a web server on Heroku you bind to the $PORT Heroku tells you to bind to.
When you visit your deployed app you don't specify a port. You just connect to yourappname.heroku.com. The DNS automatically translates it into ipaddress:port.
So on your frontend you just point to yourappname.heroku.com instead of ipaddress:port.

NestJS Multer Amazon S3 issues uploading multiple files

I'm using NestJS, Node, and Express for my backend and Angular for my frontend. I have a stepper where the user steps through and enters in information about themselves as well as a profile photo and any photos of their art that they want to post (it's a rough draft). I'm sending the files to the backend with this code:
<h2>Upload Some Photos</h2>
<label for="singleFile">Upload file</label>
<input id="singleFile" type="file" [fileUploadInputFor]= "fileUploadQueue"/>
<br>
<mat-file-upload-queue #fileUploadQueue
[fileAlias]="'file'"
[httpUrl]="'http://localhost:3000/profile/artPhotos'">
<mat-file-upload [file]="file" [id]="i" *ngFor="let file of fileUploadQueue.files; let i = index"></mat-file-upload>
</mat-file-upload-queue>
The front-end sends the photos as an array of files; I tried to change it so that it just sent a single file but could not get it working. I'm less focused on that because the user may need to upload multiple files, so I want to figure it out regardless. On the backend, I'm using multer, multer-s3, and AWS-SDK to help upload the files however it isn't working. Here is the controller code:
#Post('/artPhotos')
#UseInterceptors(FilesInterceptor('file'))
async uploadArtPhotos(#Req() req, #Res() res): Promise<void> {
req.file = req.files[0];
delete req.files;
// tslint:disable-next-line:no-console
console.log(req);
await this._profileService.fileupload(req, res);
}
Here is ProfileService:
import { Profile } from './profile.entity';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { ProfileDto } from './dto/profile.dto';
import { Req, Res, Injectable, UploadedFile } from '#nestjs/common';
import * as multer from 'multer';
import * as AWS from 'aws-sdk';
import * as multerS3 from 'multer-s3';
const AWS_S3_BUCKET_NAME = 'blah';
const s3 = new AWS.S3();
AWS.config.update({
accessKeyId: 'blah',
secretAccessKey: 'blah',
});
#Injectable()
export class ProfileService {
constructor(#InjectRepository(Profile)
private readonly profileRepository: Repository<Profile> ){}
async createProfile( profileDto: ProfileDto ): Promise<void> {
await this.profileRepository.save(profileDto);
}
async fileupload(#Req() req, #Res() res): Promise<void> {
try {
this.upload(req, res, error => {
if (error) {
// tslint:disable-next-line:no-console
console.log(error);
return res.status(404).json(`Failed to upload image file: ${error}`);
}
// tslint:disable-next-line:no-console
console.log('error');
return res.status(201).json(req.file);
});
} catch (error) {
// tslint:disable-next-line:no-console
console.log(error);
return res.status(500).json(`Failed to upload image file: ${error}`);
}
}
upload = multer({
storage: multerS3({
// tslint:disable-next-line:object-literal-shorthand
s3: s3,
bucket: AWS_S3_BUCKET_NAME,
acl: 'public-read',
// tslint:disable-next-line:object-literal-shorthand
key: (req, file, cb) => {
cb(null, `${Date.now().toString()} - ${file.originalname}`);
},
}),
}).array('upload', 1);
}
I haven't implemented any middleware extending multer, but I don't think I have to. You can see in the controller I erase the files property on req and replace it with the file where it's value is just the first member of the files array but that was just to see if it would work if I send it something it was expecting, but it did not work then. Does anyone have any ideas regarding how I can fix this? Or can anyone at least point me in the right direction with a link to a relevant tutorial or something?
My first guess would be that you are using the FileInterceptor and multer. I assume FileInterceptor adds multer in the controller which makes it available to the #UploadedFile decorator. Which could cause a conflict to your later use of multer. Try removing the interceptor and see if that fixes the issue.
Also I am attaching how I am doing file uploads. I am only uploading single images and I am using the AWS SDK so I don't have to work with multer directly, but here is how I am doing it, it might be helpful.
In the controller:
#Post(':id/uploadImage')
#UseInterceptors(FileInterceptor('file'))
public uploadImage(#Param() params: any, #UploadedFile() file: any): Promise<Property> {
return this.propertyService.addImage(params.id, file);
}
Then my service
/**
* Returns a promise with the URL string.
*
* #param file
*/
public uploadImage(file: any, urlKey: string): Promise<string> {
const params = {
Body: file.buffer,
Bucket: this.AWS_S3_BUCKET_NAME,
Key: urlKey
};
return this.s3
.putObject(params)
.promise()
.then(
data => {
return urlKey;
},
err => {
return err;
}
);
}
Thanks Jedediah, I like how simple your code is. I copied your code however it still wasn't working. Turns out you have to instantiate the s3 object after you update the config with your accesskey and secretID.

"fake path" issue using multer+angular 6

I spend the last 3 days to fix the problem , but i didnt figure out yet the issue.
Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64
Angular: 6.0.6
multer. 1.3.1
my code at "childApi" using multer staff :
var store = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.' + file.originalname);
}
});
var upload = multer({ storage: store , }).single('file');
router.post('/upload', function (req, res, next) {
upload(req, res, function (err) {
if (err) {
return console.log ('not working well')
}
//do all database record saving activity
return res.json({ originalname: req.file.originalname, uploadname: req.file.filename });
});
});
my code at "add-child" component using simple code :
import { Component, OnInit, Inject } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '#angular/material';
import { Child } from '../../models/child';
import { ChildService } from '../../services/child.service';
import {FileUploader } from 'ng2-file-upload';
const uri = 'http://localhost:3000/childApi/upload';
#Component({
selector: 'app-add-child',
templateUrl: './add-child.component.html',
styleUrls: ['./add-child.component.css']
})
export class AddChildComponent implements OnInit {
newChild = new Child;
uploader: FileUploader = new FileUploader({ url: uri });
attachmentList: any = [];
constructor(private childService: ChildService,
private route: ActivatedRoute,
private router: Router,
public dialogRef: MatDialogRef<AddChildComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
this.attachmentList.push(JSON.parse(response));
};
}
The problem is that after I upload the file to the folder "uploads"
,I want to display my new photo on the screen.
The console give me this error :
GET unsafe:C:\fakepath\child+thinking.jpg 0 ()
If someone help its will be amazing.
Thanks...
I figure out what to do , I just put this sentences inside my code at "add-child" component using :
this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
this.newChild.user_img = JSON.parse(response).uploadname;
this.attachmentList.push(JSON.parse(response));
};
}
As I understand from your post that you have doing a model named child inside your project so if you have can I take a look on it I will be grateful because I'm doing the same task except still getting the error:
Access to XMLHttpRequest at 'http://localhost:4000/file/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
core.js:1449 ERROR SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at FileUploader.UploadFileComponent.uploader.onCompleteItem (upload-file.component.ts:27)
at FileUploader.push../node_modules/ng2-file-upload/file-upload/file-uploader.class.js.FileUploader._onCompleteItem (file-uploader.class.js:199)
at XMLHttpRequest.xhr.onerror [as __zone_symbol__ON_PROPERTYerror] (file-uploader.class.js:268)`
javascript html typescript angular6 multer

Categories