Can't send FormData to NodeJS server in MERN Stack App with TypeScript - node.js

I'm stuck with that request already. I'm trying to send FormData to NodeJS server but all I got in backend when I console.log the req.body is empty object. I checked the FormData keys/values and it's all good.
Here is my POST request in frontend:
const createProduct = (e: any) => {
e.preventDefault();
const data = new FormData()
data.append("name", name)
data.append("description", description)
data.append("price", price)
for (const colorAndImage of colorsAndImages) {
data.append('images', colorAndImage.images[1]);
data.append('colors', colorAndImage.colors);
}
data.append("type", type)
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]); // the keys/values are correct
}
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: data
})
.then(response => {
if (response.status === 201) {
setName('')
setDescription('')
setPrice('')
setType('')
} else if (response.status === 500) {
console.log('error');
}
})
.catch(error => console.log(error));
}
And my controller in backend:
productController.post('/create', async (req: Request, res: Response) => {
console.log(req.body)
try {
const data = {
name: req.body.name,
description: req.body.description,
price: req.body.price,
colors: req.body.colors,
images: req.body.images,
type: req.body.type,
likes: req.body.likes
}
let product = await create(data)
res.status(201).json(product)
} catch (error) {
console.log(error);
//res.status(500).json({error: error})
}
})
Even that I obviously send some data, the req.body is an empty object and I got that error:
Error: Product validation failed: name: Path 'name' is required.,
description: Path 'description' is required., price: Path 'price' is
required., type: Path 'type' is required.
at ValidationError.inspect
UPDATE
My express config:
import express, { Application } from 'express';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import auth from '../middlewares/auth';
const corsConfig: cors.CorsOptions = {
credentials: true,
origin: ['http://localhost:3000', 'http://localhost:2000']
}
export default function (app: Application) {
app.use(cors(corsConfig))
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json())
app.use(auth())
}
And root server:
import express, { Application } from "express";
import routes from './routes'
import config from './config/config'
import mongooseConfig from './config/mongoose'
import expressConfig from './config/express'
const app: Application = express()
expressConfig(app);
mongooseConfig();
app.use(express.json())
app.use(routes)
app.listen(config.PORT, () => console.log(`Server is listening on port ${config.PORT}`))
Routes file:
import { Router } from "express";
import authController from "./controllers/authController";
import productController from "./controllers/productController";
const routes = Router()
routes.use('/auth', authController)
routes.use('/products', productController)
export default routes;

Maybe you can just submit it as JSON instead of Form data, this works always :smile:
const createProduct = (e: any) => {
e.preventDefault();
const data = {
"name": name,
"description": description,
"price": price,
"colorsAndImages": colorsAndImages,
"type": type,
};
// Please check mappings as I just transferred what you had :smile:
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: JSON.stringify(data),
})
.then(response => {
if (response.status === 201) {
setName('')
setDescription('')
setPrice('')
setType('')
} else if (response.status === 500) {
console.log('error');
}
})
.catch(error => console.log(error));
}

Related

How I can use sendFile in fastify?

Server.ts
import fastify from "fastify";
import cookie from 'fastify-cookie';
import apiRoute from './routes/api';
import jwtPlugin from "./plugins/jwtPlugin";
import closePlugin from "./plugins/closePlugin";
import path from "path";
const PORT = parseInt(process.env.PORT!, 10)
export default class Server {
app = fastify({ logger: true })
constructor() {
this.setup()
}
setup() {
this.app.get('/', (request, reply) => {
reply.send({ hello: 'world' })
})
this.app.register(apiRoute, { prefix: '/api' })
this.app.register(cookie)
this.app.register(require('fastify-url-data'))
this.app.register(jwtPlugin)
this.app.register(closePlugin)
this.app.setErrorHandler((error, request, reply) => {
reply.send({
statusCode: error.statusCode,
name: error.name,
message: error.message,
validation: error.validation,
stack: error.stack,
})
})
this.app.register(require('fastify-rate-limit'), {
max: 100,
timeWindow: '1 minute'
})
this.app.register(require('fastify-static'), {
root: path.join(__dirname, 'public')
})
}
version/index.ts
const versionRoute: FastifyPluginCallback = (fastify, opts, done) => {
//Todo 1. get version of app
//Define request body to fastify
fastify.post(
//Route
'/version_info',
async (request, reply) => {
try {
const result: VersionBody[] = await Version.getVersionInfo("testServer")
reply.send(result[0])
} catch (error) {
reply.status(500)
reply.send({
code: 500,
error: "Version Error",
message: error
})
}
}
)
//Todo 2. get update file
//Define request body to fastify
fastify.get('/update_file', function (req, reply) {
reply.sendFile(...)
})
done()
}
export default versionRoute
Hi, I have a question.
I want to send the file, when request to specific url.
So, I install fastify-specific and register.
But, it show error message like,
'FastifyReply<Server, IncomingMessage, ServerResponse, RouteGenericInterface, unknown>' type does not have property 'sendFile'
How I can register reply.sendFile in fastify?
or Is there any way to send file in fastify?
If you know about it, please help me.

Next.js / Node.js (Express): Set Cookies (with httpOnly) are in the response header but not in the browser storage

Server: Node.js, express, Type-Graphql with Apollo Server
In index.ts:
import 'reflect-metadata';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { buildSchema } from 'type-graphql';
import { createConnection } from 'typeorm';
import { verify } from 'jsonwebtoken';
import coockieParser from 'cookie-parser';
import cors from 'cors';
import User from './entity/User';
import UserResolver from './resolvers';
import { createAccessToken, createRefreshToken, sendRefreshToken } from './auth';
require('dotenv').config();
const corsOptions = {
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Access-Token', 'Authorization'],
credentials: true, // this allows to send back (to client) cookies
methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
origin: 'http://localhost:3000',
preflightContinue: false,
};
(async () => {
const PORT = process.env.PORT || 4000;
const app = express();
app.use(coockieParser());
app.use(cors(corsOptions));
// -- non graphql endpoints
app.get('/', (_, res) => {
res.send('Starter endpoint');
});
app.post('/refresh_token', async (req, res) => {
const token = req.cookies.jid;
if (!token) {
return res.send({ ok: false, accessToken: '' });
}
let payload: any = null;
try {
payload = verify(token, process.env.REFRESH_TOKEN_SECRET!);
} catch (e) {
console.log(e);
return res.send({ ok: false, accessToken: '' });
}
// token is valid, and the access token can be send back
const user = await User.findOne({ id: payload.userId });
if (!user) {
return res.send({ ok: false, accessToken: '' });
}
if (user.tokenVersion !== payload.tokenVersion) {
return res.send({ ok: false, accessToken: '' });
}
sendRefreshToken(res, createRefreshToken(user));
return res.send({ ok: true, accessToken: createAccessToken(user) });
});
//--
// -- db
await createConnection();
// --
// -- apollo server settings
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [UserResolver],
}),
context: ({ req, res }) => ({ req, res }),
});
await apolloServer.start();
apolloServer.applyMiddleware({
app,
cors: false,
});
// --
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});
})();
Login mutation in the UserResolver:
//..
#Mutation(() => LoginResponse)
async login(
#Arg('email') email: string,
#Arg('password') password: string,
#Ctx() { res }: AuthContext,
): Promise<LoginResponse> {
const user = await User.findOne({ where: { email } });
if (!user) {
throw new Error('Incorrect email');
}
const valid = await compare(password, user.password);
if (!valid) {
throw new Error('Incorrect password');
}
sendRefreshToken(res, createRefreshToken(user));
return {
accessToken: createAccessToken(user),
user,
};
}
//..
When handling authentification, the cookies are set in the response header as follows:
//..
export const createAccessToken = (user: User) => sign({ userId: user.id }, process.env.ACCESS_TOKEN_SECRET!, { expiresIn: '10m' });
export const createRefreshToken = (user: User) => sign({ userId: user.id, tokenVersion: user.tokenVersion }, process.env.REFRESH_TOKEN_SECRET!, { expiresIn: '7d' });
export const sendRefreshToken = (res: Response, refreshToken: string) => {
res.cookie('jid', refreshToken, {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/refresh_token',
});
};
//..
Client: Next.js, Graphql with URQL
In _app.tsx:
/* eslint-disable react/jsx-props-no-spreading */
import * as React from 'react';
import Head from 'next/head';
import { AppProps } from 'next/app';
import { ThemeProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline';
import { CacheProvider, EmotionCache } from '#emotion/react';
import { createClient, Provider } from 'urql';
import theme from '../styles/theme';
import createEmotionCache from '../lib/createEmotionCache';
import '../styles/globals.css';
// Client-side cache shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
interface IAppProps extends AppProps {
// eslint-disable-next-line react/require-default-props
emotionCache?: EmotionCache;
}
const client = createClient({
url: 'http://localhost:4000/graphql',
fetchOptions: {
credentials: 'include',
},
});
const App = (props: IAppProps) => {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
return (
<Provider value={client}>
<CacheProvider value={emotionCache}>
<Head>
<title>Client App</title>
</Head>
<ThemeProvider theme={theme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
</Provider>
);
};
export default App;
Login page does not rely on SSR or SSG (so it is CSR):
import React from 'react';
import LoginForm from '../components/LoginForm/LoginForm';
import Layout from '../layouts/Layout';
interface ILoginProps {}
const Login: React.FC<ILoginProps> = () => (
<Layout
showNavbar={false}
showTransition={false}
maxWidth='xs'
>
<LoginForm />
</Layout>
);
export default Login;
The mutation is used in the LoginForm component to request an access token and set refresh token in the browser cookies:
import React from 'react';
import { useRouter } from 'next/router';
import { useLoginMutation } from '../../generated/graphql';
//...
const LoginForm = () => {
//..
const [, login] = useLoginMutation();
const router = useRouter();
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (disabledSubmit) {
setShowFormHelper(true);
} else {
const res = await login({
email, // from the state of the component
password,
});
if (res && res.data?.login) {
console.log(res.data.login.accessToken);
router.push('/home');
setShowFormHelper(false);
} else {
setHelper('Something went wrong');
}
}
};
//..
};
export default LoginForm;
Issue
So, the problem is that the login response has set-cookie in the header, but the cookie still isn't set in the browser:
Question
Previously, I've implemented the same authentication scheme using the same server code but create-react-app on the client. Everything worked just fine. So, why isn't it working now with next.js? What am I missing?
Work Around
I can use something like cookies-next to put cookies into the storage. The refresh token then would need to be passed in the response data:
import React from 'react';
import { useRouter } from 'next/router';
import { useLoginMutation } from '../../generated/graphql';
import { setCookies } from 'cookies-next';
//...
const LoginForm = () => {
//..
const [, login] = useLoginMutation();
const router = useRouter();
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (disabledSubmit) {
setShowFormHelper(true);
} else {
const res = await login({
email, // from the state of the component
password,
});
if (res && res.data?.login) {
console.log(res.data.login.accessToken);
setCookies('jid', res.data.login.refreshToken);
router.push('/home');
setShowFormHelper(false);
} else {
setHelper('Something went wrong');
}
}
};
//..
};
export default LoginForm;
setCookie accepts options. However, the httpOnly can't be set to true in this case anyway.
Updates
It turns out everything above works in Firefox, but not in Chrome.
in res.cookie defined in the express server, use sameSite:'lax' instead of strict. this may solve the issue.

Using loopback4 and graphQL together

import {Lb4Application} from './application';
import {ApplicationConfig} from '#loopback/core';
import graphqlHTTP from 'express-graphql';
import {createGraphQLSchema} from 'openapi-to-graphql';
import {Oas3} from 'openapi-to-graphql/lib/types/oas3';
export {Lb4Application};
export async function main(options: ApplicationConfig = {}) {
const app = new Lb4Application(options);
await app.boot();
await app.start();
const url: string = <string>app.restServer.url;
console.log(`REST API Server is running at ${url}`);
const graphqlPath = '/graphql';
const oas: Oas3 = <Oas3>(<unknown>app.restServer.getApiSpec());
const {schema} = await createGraphQLSchema(oas, {
strict: false,
viewer: false,
baseUrl: url,
headers: {
'X-Origin': 'GraphQL',
},
tokenJSONpath: '$.jwt',
});
const handler: graphqlHTTP.Middleware = graphqlHTTP(
(request, response, graphQLParams) => ({
schema,
pretty: true,
graphiql: true,
context: {jwt: getJwt(request)},
}),
);
// Get the jwt from the Authorization header and place in context.jwt, which is then referenced in tokenJSONpath
function getJwt(req: any) {
if (req.headers && req.headers.authorization) {
return req.headers.authorization.replace(/^Bearer /, '');
}
}
app.mountExpressRouter(graphqlPath, handler);
console.log(`Graphql API: ${url}${graphqlPath}`);
return app;
}
I have taken this code from this github issue, and I still cannot seem to get it to run.
The error is get is
Error: Invalid specification provided
When i just use an express server, and run npx openapi-to-graphql --port=3001 http://localhost:3000/openapi.json --fillEmptyResponses The graphql is served correctly.
I need to get the example code running, as it seems to be the only way to pass JWT token headers correctly when using loopback4 and graphql together
This is how i solved it for anyone that needs help:
/* eslint-disable #typescript-eslint/no-explicit-any */
import {Lb4GraphqlPocApplication} from './application';
import {ApplicationConfig} from '#loopback/core';
const graphqlHTTP = require('express-graphql');
const {createGraphQLSchema} = require('openapi-to-graphql');
const fetch = require('node-fetch');
export {Lb4GraphqlPocApplication};
export async function main(options: ApplicationConfig = {}) {
console.log('hello world!')
const app = new Lb4GraphqlPocApplication(options);
await app.boot();
await app.start();
const url = app.restServer.url;
const graphqlPath = '/graphql';
console.log(`REST Server is running at ${url}`);
console.log(`Try ${url}/ping`);
// replace with process.env.{active-environment} once deployments setup
const openApiSchema = 'http://localhost:3000/openapi.json';
const oas = await fetch(openApiSchema)
.then((res: any) => {
console.log(`JSON schema loaded successfully from ${openApiSchema}`);
return res.json();
})
.catch((err: any) => {
console.error('ERROR: ', err);
throw err;
});
const {schema} = await createGraphQLSchema(oas, {
strict: false,
viewer: true,
baseUrl: url,
headers: {
'X-Origin': 'GraphQL',
},
tokenJSONpath: '$.jwt',
});
const handler = graphqlHTTP(
(request: any, response: any, graphQLParams: any) => ({
schema,
pretty: true,
graphiql: true,
context: {jwt: getJwt(request)},
}),
);
// Get the jwt from the Authorization header and place in context.jwt, which is then referenced in tokenJSONpath
function getJwt(req: any) {
if (req.headers && req.headers.authorization) {
return req.headers.authorization.replace(/^Bearer /, '');
}
}
app.mountExpressRouter(graphqlPath, handler);
console.log(`Graphql API: ${url}${graphqlPath}`);
return app;
}

React app on Heroku cannot make a POST request

I+m playing with the Chatkit API, and when running a React app in my local machine everything seems to work fine, but when I pushed it to Heroku, every time it tries to do a POST request through the server, it gives Failed to load resource: net::ERR_CONNECTION_REFUSED and index.js:1375 error TypeError: Failed to fetch
This is my server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const Chatkit = require('#pusher/chatkit-server')
const app = express()
const chatkit = new Chatkit.default({
instanceLocator: I HAVE MY INSTANCE LOCATOR HERE,
key: I HAVE MY KEY HERE,
})
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
app.post('/users', (req, res) => {
const { username } = req.body
chatkit
.createUser({
id: username,
name: username
})
.then(() => res.sendStatus(201))
.catch(error => {
if (error.error === 'services/chatkit/user_already_exists') {
res.sendStatus(200)
} else {
res.status(error.status).json(error)
}
})
})
app.post('/authenticate', (req, res) => {
const authData = chatkit.authenticate({ userId: req.query.user_id })
res.status(authData.status).send(authData.body)
})
const PORT = 3001
app.listen(PORT, err => {
if (err) {
console.error(err)
} else {
console.log(`Running on port ${PORT}`)
}
})
And then this is my App.js
import React, { Component } from 'react'
import UsernameForm from './components/UsernameForm'
import ChatScreen from './ChatScreen'
class App extends Component {
constructor() {
super()
this.state = {
currentUsername: '',
currentScreen: 'WhatIsYourUsernameScreen'
}
this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this)
}
onUsernameSubmitted(username) {
fetch('http://localhost:3001/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username }),
})
.then(response => {
this.setState({
currentUsername: username,
currentScreen: 'ChatScreen'
})
})
.catch(error => console.error('error', error))
}
render() {
if (this.state.currentScreen === 'WhatIsYourUsernameScreen') {
return <UsernameForm onSubmit={this.onUsernameSubmitted} />
}
if (this.state.currentScreen === 'ChatScreen') {
return <ChatScreen currentUsername={this.state.currentUsername} />
}
}
}
export default App
I believe that it's at this time that it breaks
return <UsernameForm onSubmit={this.onUsernameSubmitted} />
When submitting it is expected to make a POST request to create a new user, and React to load the new component, but it just stays in the UsernameForm component, and in the console I can see these errors:
Failed to load resource: net::ERR_CONNECTION_REFUSED
index.js:1375 error TypeError: Failed to fetch
Probably the issue is the localhost in the endpoint at onUsernameSubmitted. We need more details about how your application is deployed and how the communication between server and spa is designed. If you have an Nginx you can set the redirect there.
I see three potential reasons of the error:
Database has to be well deployed and db:migrate triggered to define the db schema.
If 1) is fulfilled, then make sure whether your graphql path points to server url my-app.herokuapp.com not to localhost:<port>, The easiest way to check that is via browser/devtools/network query.
(optional) I use ApolloClient and my rule process?.env?.NODE_ENV ? 'prod_url' : 'dev_url' didn't work because of missing vars definitions in webpack:
new DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),```

Unexepected token U in JSON at position 0

I have a problem with MEAN Stack.
I have an Angular Form with good values to creat a company id DB with Node Express in backend. I have an error that the JSON in Node is Undefined. but i don't understand why ?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userboRoutes = require('./routes/userbo');
const companyRoutes = require('./routes/company');
const path = require('path');
mongoose.connect('mongodb://127.0.0.1/aya', {useNewUrlParser: true})
.then(() => {
console.log('Successfully connected to MongoDB AYA!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB! AYA');
console.error(error);
});
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(bodyParser.json());
app.use('/api/company', companyRoutes);
app.use('/api/authbo', userboRoutes);
module.exports = app;
routes\company.js
const express = require('express');
const router = express.Router();
const companyCtrl = require('../controllers/company');
const Company = require('../models/company');
router.post('/', companyCtrl.createCompany);
router.get('/:id', companyCtrl.getOneCompany);
router.put('/:id', companyCtrl.modifyCompany);
router.delete('/:id', companyCtrl.deleteCompany);
router.get('/', companyCtrl.getAllCompany);
module.exports = router;
controller\company.js
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
Angular Component :
this.companyService.CreateCoData(company).then(
() => {
this.CreateCoForm.reset();
this.router.navigate(['home']);
},
(error)=> {
this.loading = false;
this.errorMessage = error.message;
}
);
Company service
import { Router } from '#angular/router';
import { Company } from './../models/company.model';
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
export class CompanyService {
constructor(private router: Router,
private http: HttpClient) { }
company: Company[];
companySubject = new Subject<Company[]>();
public company$ = new Subject<Company[]>();
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
I got this error :
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at exports.createCompany (E:\MEAN\BACKEND\controllers\company.js:7:29)
Or in the Request payload (Chrome dev tools network) the json is correct.
I don't understand why the req json in undefined ?
Please help me to understand :)
UPDATE
Just work with POSTMAN :
and update the company.js like this
exports.createCompany = (req, res, next) => {
console.log( req.body);
// req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.coid,
coname: req.body.coname,
service: req.body.service,
address: req.body.address,
state: req.body.state,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
size: req.body.size,
domain: req.body.domain,
duns: req.body.duns,
tid1: req.body.tid1,
numid1: req.body.numid1,
tid2: req.body.tid2,
numid2: req.body.numid2,
tid3: req.body.tid3,
numid3: req.body.numid3,
bankname: req.body.bankname,
bicswift: req.body.bicswift,
iban: req.body.iban,
datecreat: req.body.datecreat,
bogid: req.body.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
I think the problem come from a bad data format. But How to set it correctly ?
The .save function returns a callback and not a promise.
So if you modify your request handler as follows it will work:
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save(function (err, newCompany) {
if (err) {
return res.status(400).json({ error: error });
}
return res.status(201).json(newCompany);
});
};
So I Found the SOLUTION ^^ So proud ** ((^o^)/)**
After the update in the first post, I see that the problem is Content-type Error.
So in ** company service** (Angular) I add this to Force JSON Type !
import { HttpClient, HttpClientModule,** HttpHeaders** } from '#angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company, **this.httpOptions**).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}

Resources