Sending data with vanilla JS ajax and reading it with Node api - javascript

I have this code on my client side:
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(body);
fetch('http://localhost:4000/', {
method: 'POST',
body: body.toString(),
}).then(r => console.log(r)).catch(e => console.log(e));
}
And this kind of works. It logs the object to the console, and sends something to the back end.
Here's my Node call:
var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());
var a = '=';
router.post('/', (req, res, next) => {
console.log('mailing');
console.log(a);
console.log(req.body);
a += '=';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: '******',
pass: '******'
}
});
let mailOptions = {
from: `${req.body.name} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from UczSieApp contact form', // Subject line
text: 'Hello world ', // plaintext body
html: `
<h4>Imie: ${req.body.name}</h4>
<h4>Email: ${req.body.email}</h4>
<h4>Powod kontaktu: ${req.body.contactReason}</h4>
<p>Wiadomosc: ${req.body.additionalInfo}</p>
`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
);
module.exports = router;
So what the code does right now:
The object is being created, something (not sure what exactly) is being send to Node back-end, and an email is being sent. But req.body is logged as {}.
What I want to do:
Read the values sent to the back-end as body and send an email with this data.
What am I missing?

I used GET instead of POST and this solved my problems. It is kind of a cheat but it works.

should add to fetch
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body),
all correct code
frontend
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(body);
fetch('http://localhost:4000/', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body),
method: 'POST',
}).then(r => console.log(r)).catch(e => console.log(e));
}
backend
var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());
var a = '=';
router.post('/', (req, res, next) => {
console.log('mailing');
console.log(a);
console.log(req.body);
a += '=';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: '******',
pass: '******'
}
});
let mailOptions = {
from: `${req.body.name} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from UczSieApp contact form', // Subject line
text: 'Hello world ', // plaintext body
html: `
<h4>Imie: ${req.body.name}</h4>
<h4>Email: ${req.body.email}</h4>
<h4>Powod kontaktu: ${req.body.contactReason}</h4>
<p>Wiadomosc: ${req.body.additionalInfo}</p>
`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
);
module.exports = router;

Related

POST Request Returns Empty First TIme, Then Isn't empty every time after

For Some Reason, The POST request for a link below returns empty the first time and then isn't empty every time after. If I change the email and make a new request, it returns the last user called for. It seems that the array is retaining its value on the server. I used the array because a global variable wasn't being defined by the promise chain from the fetch call. Below is the code for the server, as well as the request from Postman. I think this can be solved by figuring out how to define the global var in the fetch call, but every solution I've researched has failed.
Server Side Code:
//add in external libraries and requirements
const dotenv = require('dotenv')
dotenv.config({ path: './.env' })
const express = require('express')
const app = express()
const port = process.env.PORT || 8080
var cors = require('cors')
const fs = require('fs')
const fetch = require("node-fetch");
var bodyParser = require('body-parser')
let resultarr = []
let resultarr1 = []
//encryption
const key = process.env.KEY
function fakeMathRandom(callBack) {
if(!callBack) throw new Error("Must provide callBack function");
let seed=0;
const randomOutputs = [0.04,0.08,0.15,0.16,0.23,0.42,0.52,0.65,0.79,0.89];
const Math_random = Math.random;
Math.random = function() {return randomOutputs[seed++ % 10];}
const callbackOutput = callBack();
Math.random = Math_random;
return callbackOutput;
}
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
//serve static files
var publicdir = __dirname + '/public';
app.use(function(req, res, next) {
console.log(req)
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
}
else
next();
});
app.use(cors())
app.use(express.static(publicdir));
// POST request
app.post('/email', jsonParser, function (req, response) {
var email = (req.body.email)
var password = (req.body.password)
var result;
var url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyC-BUGGSsvUX8z4W1LcsJzS59yrL4__EsE";
var payload = {
email: email,
password: password,
returnSecureToken: true
};
var options = {
method: 'post',
contentType: 'application/json',
body: JSON.stringify(payload)
};
//make fetch call
load =(url, options) =>{
return fetch(url, options).then(response => response.json());
}
load(url,options).then(result => {
// result is the parsed JSON - i.e. a plan ol' javascript object
resultarr[0] = result
});
response.send(resultarr[0])
})
app.get('/test', (req, res) => {
res.send(resultarr[0]);
});
app.listen(port, () => {
console.log(`app listening at port:${port}`)
});
Postman API Request (Curl)
curl --location --request POST 'https://splurket.us/email' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "testuser#gmail.com",
"password": "Testing123",
"returnSecureToken": true
}'
Emails You Can use For Testing The Endpoint:
Email: Testinguser#gmail.com | Password: Testing123
Email: Testinguser1#gmail.com | Password: Testing123
I solved the problem. So In Express, you can just use the async function shown below and then you can use await since it is inside an async function.
app.post('/email', jsonParser, async function (req, response) {
var email = req.body.email
var password = req.body.password
var result;
var url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyC-BUGGSsvUX8z4W1LcsJzS59yrL4__EsE";
var payload = {
email: email,
password: password,
returnSecureToken: true
};
var options = {
method: 'post',
contentType: 'application/json',
body: JSON.stringify(payload)
};
const res = await fetch(url, options);
const result = await res.json();
response.send(result)
})

NodeJS App for Rocket Chat iframe auth throws SyntaxError: Unexpected token (

I have a nodejs app that throws the error every time I try and start the app using the command "node index.js":
app.post('/login', async (req, res) => {
^
SyntaxError: Unexpected token (
I understand how generic this error is, but I need a bit of direction. This application specifically is for iframe-auth detailed in rocket.chats documentation for utilizing a 3rd party API to login instead rocket chat's native login system.
The entire code of the app is here:
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request-promise');
var session = require('express-session');
const cookieParser = require('cookie-parser');
var app = express();
const rocketChatServer = '*redacted*';
const rocketChatAdminUserId = '*redacted*';
const rocketChatAdminAuthToken = '*redacted*';
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//CORS in case you need
app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', '*redacted*');
res.set('Access-Control-Allow-Credentials', 'true');
next();
});
// define middleware
const middleware = [
cookieParser(),
session({
secret: 'super-secret-key',
key: 'super-secret-cookie',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1209600000 } // two weeks in miliseconds
})
]
app.use(middleware);
//var createOrLoginUser = require('./rocketchat');
app.get('/', (req, res) => {
if(req.session.rocketchatAuthToken){
res.send(`
<html>
<body>
<iframe width='100%;' height='100%' src="*redacted*"
frameborder="0"></iframe>
</body>
</html>`);
}else{
res.send(`
<form method="post" action="/login">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="firstName"
name="firstname">
<input type="text" placeholder="Email" name="email">
<input type="text" placeholder="Pass" name="password">
<input type="submit" value="Submit">
</form>
`);
}
})
app.post('/login', async (req, res) => {
// ....CODE TO LOGIN USER
var username = req.body.username;
var pass = req.body.password;
var email = req.body.email;
var name = req.body.firstname;
// Creating or login user into Rocket chat
try {
// Request of login for 3rd party API
var options = { method: 'GET',
url: '*redacted*',
qs:
{ hashKey: '*redacted*',
sitename: username,
password: pass },
headers:
{ 'Postman-Token': '*redacted*',
'Cache-Control': 'no-cache' } };
const third_party_response = await request(options);
var result_third_party = JSON.parse(third_party_response);
console.log(result_third_party);
console.log(result_third_party.email);
if(result_third_party.email != ''){
// Request of login for Rocket Chat
var options = { method: 'POST',
url: `${rocketChatServer}/api/v1/login`,
headers:
{ 'Postman-Token': '*redacted*',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { username: username, password: pass } };
const response = await request(options);
var result = JSON.parse(response);
req.session.rocketchatAuthToken = result.data.authToken;
res.redirect('/');
}else{
res.send('You are not registered with 3rd party API!');
}
} catch (ex) { console.log('CATHCh');
if (ex.statusCode === 401) {
// User does not exist, creating user
var options = { method: 'POST',
url: '*redacted*',
headers:
{ 'Postman-Token': '*redacted*',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded',
'X-User-Id': rocketChatAdminUserId,
'X-Auth-Token': rocketChatAdminAuthToken },
form:
{ name: name ,
email: email,
password: pass,
username: username } };
const response_register = await request(options);
var result_register = JSON.parse(response_register);
if(result_register.success){
// on success login users
var options = { method: 'POST',
url: `${rocketChatServer}/api/v1/login`,
headers:
{ 'Postman-Token': '*redacted*',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { username: username, password: pass } };
const response = await request(options);
var result = JSON.parse(response);
req.session.rocketchatAuthToken = result.data.authToken;
res.redirect('/');
}else{
console.log('Failed to create account');
}
// Perfom login
//return await loginUser(email, password);
} else {
throw ex;
}
}
})
// This method will be called by Rocket.chat to fetch the login token
app.get('/api/v1/rocket_chat_auth_get', (req, res) => {
if (req.session.rocketchatAuthToken) {
res.send({ loginToken: req.session.rocketchatAuthToken })
return;
} else {
res.status(401).json({ message: 'User not logged in'});
return;
}
})
// This method will be called by Rocket.chat to fetch the login token
// and is used as a fallback
app.get('/api/v1/rocket_chat_iframe', (req, res) => {
const rocketChatServer = '*redacted*';
if (req.session.rocketchatAuthToken) {
return res.send(`<script>
window.parent.postMessage({
event: 'login-with-token',
loginToken: '${ req.session.rocketchatAuthToken }'
}, '${ rocketChatServer }');
</script>
`)
return;
} else {
return res.redirect('/login');
}
})
app.listen(3030, function () {
console.log('Example app listening on port 3030!');
});
You must be using the wrong version of node. The async keyword requires node 8 or later.

how to call a post request from button? node express

how do i call controller from a click button?
i tried into postman it works well.. but i cannot call it into button on my front-end.
i am using nodemailer and node express to send email..
here's my code..
is this correct? - thanks in advance.
i am figuring out if my code is in correct or not.
mailController.js
// mail controller routes
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
// get /api/mail/
router.get('/send-email', (req,res) => {
res.send('GET response');
});
// post /api/mail/
router.route('/send-email').post((req,res) => {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: 'dev.xxx#gmail.com',
clientId: 'xxx-xxx.apps.googleusercontent.com',
clientSecret: 'SY0-xxxx',
refreshToken: '1/xxx',
accessToken: 'ya29.xxx-xxx-xxx-xxx'
}
})
let mailOptions = {
from: 'FReyes <dev.xxx#gmail.com>',
to: 'xxx#gmail.com',
subject: 'Nodemailer test',
text: 'Hello World!!'
}
transporter.sendMail(mailOptions, function (err, res) {
if(err){
console.log('Error');
} else {
console.log('Email Sent');
}
})
});
// put /api/mail/
router.put('/send-email',(req,res) => {
res.send('PUT response');
});
// delete /api/mail/
router.delete('/send-email',(req,res) => {
res.send('DELETE response');
});
module.exports = router;
server.js
var express = require('express');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var app = express(); // Please do not remove this line, since CLI uses this line as guidance to import new controllers
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
// console.log(req);
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,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');
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
var mailController = require('./controllers/mailController');
app.use('/api/mail', mailController);
app.listen(process.env.PORT || 5015, () => {
console.log('Server is running');
});
contact.component.ts
sendMail() {
const data = {
to: 'xxx#gmail.com',
subject: 'Subject',
txt: 'hello world'
};
console.log('asd');
return this.http.post('localhost:5015/api/mail/send-email', data).map((response: Response) =>{
console.log (response.json());
});
}
html
<input type="button" value="test" (click)="sendMail(data)">
don't forget to add protocol name and return value in the map function
sendMail() {
const data = {
to: 'xxx#gmail.com',
subject: 'Subject',
txt: 'hello world'
};
console.log('asd');
return this.http.post('http://localhost:5015/api/mail/send-email', data).subscribe(data => console.log(data));
}

Gmail API sending email error 401:Invalid Credentials

I'm developing with express a web page that when the client clicks in "Send E-mail" redirect to google asking for permission to send email through the client email and after the client gave the permission redirect back and send the email.
The code so far:
'use strict';
const express = require('express');
const googleAuth = require('google-auth-library');
const request = require('request');
let router = express.Router();
let app = express();
const SCOPES = [
'https://mail.google.com/'
,'https://www.googleapis.com/auth/gmail.modify'
,'https://www.googleapis.com/auth/gmail.compose'
,'https://www.googleapis.com/auth/gmail.send'
];
const clientSecret = '***********';
const clientId = '**************';
const redirectUrl = 'http://localhost:8080/access-granted';
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
function sendEmail(auth, content, to , from, subject) {
let encodedMail = new Buffer(
`Content-Type: text/plain; charset="UTF-8"\n` +
`MIME-Version: 1.0\n` +
`Content-Transfer-Encoding: 7bit\n` +
`to: ${to}\n` +
`from: ${from}\n` +
`subject: ${subject}\n\n` +
content
)
.toString(`base64`)
.replace(/\+/g, '-')
.replace(/\//g, '_');
request({
method: "POST",
uri: `https://www.googleapis.com/gmail/v1/users/me/messages/send`,
headers: {
"Authorization": `Bearer ${auth}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"raw": encodedMail
})
},
function(err, response, body) {
if(err){
console.log(err); // Failure
} else {
console.log(body); // Success!
}
});
}
app.use('/static', express.static('./www'));
app.use(router)
router.get('/access-granted', (req, res) => {
sendEmail(req.query.code, 'teste email', 'teste#gmail.com', 'teste#gmail.com', 'teste');
res.sendfile('/www/html/index.html', {root: __dirname})
})
router.get('/request-access', (req, res) => {
res.redirect(authUrl);
});
router.get('/', (req, res) => {
res.sendFile('/www/html/index.html', { root: __dirname });
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
module.exports = app;
Every time I try to send a simple E-mail I receive the error 401: Invalid Credentials. But I'm passing in Authorization the client code auth that google sends just gave me...
The recommended way to use google APIs is to use Google API nodejs client which also provides Google OAuth flow. You can then use google.gmail('v1').users.messages.send to send the email :
const gmail = google.gmail('v1');
gmail.users.messages.send({
auth: oauth2Client,
userId: 'me',
resource: {
raw: encodedMail
}
}, function(err, req) {
if (err) {
console.log(err);
} else {
console.log(req);
}
});
auth is OAuth2, the OAuth object that can be populated with your token. You can get the token in the express session :
var oauth2Client = getOAuthClient();
oauth2Client.setCredentials(req.session["tokens"]);
which you've already stored in your OAuth callback endpoint :
var oauth2Client = getOAuthClient();
var session = req.session;
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if (!err) {
oauth2Client.setCredentials(tokens);
session["tokens"] = tokens;
res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Login failed</h1></body></html>`);
}
});
Here is a complete example inspired from this google API oauth for node.js example :
'use strict';
const express = require('express');
const google = require('googleapis');
const request = require('request');
const OAuth2 = google.auth.OAuth2;
const session = require('express-session');
const http = require('http');
let app = express();
app.use(session({
secret: 'some-secret',
resave: true,
saveUninitialized: true
}));
const gmail = google.gmail('v1');
const SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];
const clientSecret = 'CLIENT_SECRET';
const clientId = 'CLIENT_ID';
const redirectUrl = 'http://localhost:8080/access-granted';
const mailContent = "test";
const mailFrom = "someemail#gmail.com";
const mailTo = "someemail#gmail.com";
const mailSubject = "subject";
function getOAuthClient() {
return new OAuth2(clientId, clientSecret, redirectUrl);
}
function getAuthUrl() {
let oauth2Client = getOAuthClient();
let url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
//use this below to force approval (will generate refresh_token)
//approval_prompt : 'force'
});
return url;
}
function sendEmail(auth, content, to, from, subject, cb) {
let encodedMail = new Buffer(
`Content-Type: text/plain; charset="UTF-8"\n` +
`MIME-Version: 1.0\n` +
`Content-Transfer-Encoding: 7bit\n` +
`to: ${to}\n` +
`from: ${from}\n` +
`subject: ${subject}\n\n` +
content
)
.toString(`base64`)
.replace(/\+/g, '-')
.replace(/\//g, '_');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: encodedMail
}
}, cb);
}
app.use('/send-mail', (req, res) => {
let oauth2Client = getOAuthClient();
oauth2Client.setCredentials(req.session["tokens"]);
sendEmail(oauth2Client, mailContent, mailTo, mailFrom, mailSubject, function(err, response) {
if (err) {
console.log(err);
res.send(`<html><body><h1>Error</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Send mail successfull</h1><a href=/send-mail>send mail</a></body></html>`);
}
});
});
app.use('/access-granted', (req, res) => {
let oauth2Client = getOAuthClient();
let session = req.session;
let code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if (!err) {
oauth2Client.setCredentials(tokens);
session["tokens"] = tokens;
res.send(`<html><body><h1>Login successfull</h1><a href=/send-mail>send mail</a></body></html>`);
} else {
res.send(`<html><body><h1>Login failed</h1></body></html>`);
}
});
})
app.use('/', (req, res) => {
let url = getAuthUrl();
res.send(`<html><body><h1>Authentication using google oAuth</h1><a href=${url}>Login</a></body></html>`)
});
let port = process.env.PORT || 8080;
let server = http.createServer(app);
server.listen(port);
server.on('listening', function() {
console.log(`listening to ${port}`);
});

How to send a POST request from node.js Express?

Could someone show me the simplest way to send a post request from node.js Express, including how to pass and retrieve some data? I am expecting something similar to cURL in PHP.
var request = require('request');
function updateClient(postData){
var clientServerOptions = {
uri: 'http://'+clientHost+''+clientContext,
body: JSON.stringify(postData),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
request(clientServerOptions, function (error, response) {
console.log(error,response.body);
return;
});
}
For this to work, your server must be something like:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/sample/put/data', function(req, res) {
console.log('receiving data ...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
As described here for a post request :
var http = require('http');
var options = {
host: 'www.host.com',
path: '/',
port: '80',
method: 'POST'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();
you can try like this:
var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
, url: <your URL>, body: <req_body in json> }
, function(error, response, body){
console.log(body);
});
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
I use superagent, which is simliar to jQuery.
Here is the docs
And the demo like:
var sa = require('superagent');
sa.post('url')
.send({key: value})
.end(function(err, res) {
//TODO
});
Try this. It works for me.
const express = require("express");
const app = express();
app.use(express.json());
const PORT = 3000;
const jobTypes = [
{ id: 1, type: "Interior" },
{ id: 2, type: "Etterior" },
{ id: 3, type: "Roof" },
{ id: 4, type: "Renovations" },
{ id: 5, type: "Roof" },
];
app.post("/api/jobtypes", (req, res) => {
const jobtype = { id: jobTypes.length + 1, type: req.body.type };
jobTypes.push(jobtype);
res.send(jobtype);
});
app.listen(PORT, console.log(`Listening on port ${PORT}....`));

Categories