keep getting 401 using request package - node.js

My code is not working, I can't figure out why and it keeps giving me a 401 meaning the API key is missing so I don't know how this is happening and I would like to figure out what my problem is on this piece of code?
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var data = {
members: [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
url: "https://us20.api.mailchimp.com/3.0/lists/listId"
method: "POST",
headers: {
"Authorization": "mkouk24 Api Key"
},
body: jsonData
};
request(options, function(error,response,body){
if (error) {
console.log(error);
} else {
console.log(response.statusCode);
}
});
});
app.listen(3000, function() {
console.log("Server is running on port 3000!");
});

First of all, according to the documentation, I think you need to use app.use(bodyParser.json()) in order to pass parameters in post request.
Second, you should generate an API token from MailChimp and add it here Authorization": "mkouk24 Api Key"
More on that on this link: https://mailchimp.com/help/about-api-keys/

Related

Add subscriber to my mailchimp subscriber list

I am new to backend web development and trying to create subscriber through a sign up page and add them to my Mailchimp through API but I am not been able to create subscriber (subscribers are not adding in my Mailchimp audience list). Below is my code.
const port = 3000;
const https = require('node:https');
const express = require('express');
const app = express();
app.use(express.static("public"));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.sendFile(__dirname + "/signup.html")
});
app.post('/', (req, res) => {
const email = req.body.emailId;
const firstName = req.body.firstName;
const lastName = req.body.lastName;
var data = {
members: [{
email_address: email,
status: "Subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
const jsonData = JSON.stringify(data);
const url = "https://us11.api.mailchimp.com/3.0/lists/"list_id"/";
const options = {
method: "POST",
auth: "dALamyan:apiKey"
};
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end;
});
app.listen(port, () => {
console.log("app listening on port 3000.");
});
You can try my code below. It's working fine for me.
Change X in the API endpoint, listID and apiKey as per your account settings.
Cheers.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", (req, res) => {
const firstName = req.body.firstname;
const lastName = req.body.lastname;
const email = req.body.email;
const data = {
members: [{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
const jsonData = JSON.stringify(data);
const url = "https://usX.api.mailchimp.com/3.0/lists/" + listID;
const options = {
method: "POST",
auth: "archit:apiKey"
}
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
});
app.listen("3000", (req, res) => {
console.log("Server is running on port 3000.");
});

Node JS header problems with ionic

So i am using ionic framwork to make my app and using nodeJS as my backend but i am still a noob in this and i can't seem to figure it out still after 4 days so hopefully someone could answer this problem to me and why would be appreciated.
So for my ionic client side i do this to make a http.post request
progress() {
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let options = {headers: headers};
let postData = {
username: this.username,
email: this.email,
password1: this.password1,
password2: this.password2
};
this.http.post('localhost:4000/api/users', postData, options,).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
});
}
and this is what i am doing to get the data from the server but that's not working
// Packages
let express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors({origin: 'http://localhost:8100'}));
const port = 4000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Whenever you enter localhost:4000/ //
app.get('/', function (req, res) {
res.send(('Server runs'));
});
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/api/users', (req, res) => {
res.send('api/users page');
request.get({
uri: 'http://localhost:8100/create-account'
}, function (err, res, body) {
console.log('error:', err); // Print the error if one occurred and handle it
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
res.send(body);
});
});
i also tried 'http://localhost:8100' & 'localhost:8100'
so someone help me
You need to add a handler for your POST request. To do this use app.post, and it looks like this
app.post('/api/users', (req, res) => {
// You can find your data here
const data = req.body;
console.log(data);
// Send back a response
res.sendStatus(200);
});

req.body undefined in MEAN stack

I'm working on my first mean stack application and running in to a problem. I have a Blog model and I'm trying to assign the properties from the req object but its undefinded. When I do a console log of the req.body it looks like this:
{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}
but when I log the values out individually like console.log(req.body.title) its undefined. In my server.js I've included body parser and made sure the route is after incorporating body parser. So at this point I'm not sure why it would be undefined any help is appreciated.
Here is the post for the blog:
createAuthenticationHeaders() {
this.authService.loadToken();
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
authorization: this.authService.authToken
})
};
}
newBlog(blog) {
this.createAuthenticationHeaders(); // Create headers
return this.http.post(this.domain + 'blogs/newBlog', blog,
this.httpOptions);
}
This is the payload
Thanks
Here is that file
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./config/database');
const path = require('path');
const authentication = require('./routes/authentication')(router);
const blogs = require('./routes/blogs')(router);
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 8080;
mongoose.connect(config.uri, err => {
if (err) {
console.log('Connection error db ', err);
} else {
console.log('Connected to db ', config.db);
}
});
app.use(
cors({
origin: 'http://localhost:4200'
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/dist/'));
app.use('/authentication', authentication);
app.use('/blogs', blogs);
app.get('*', (req, res) => res.sendFile(__dirname +
'/client/dist/index.html'));
app.listen(port, () => console.log(`App listening on port ${port}`));
When I do a console log of the req.body it looks like this:
{ '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''}
You're posting a JSON, which has another JSON as property, therefore req.body.title is undefined. Check your client side, because you're posting the JSON wrong.
// This is what you say you're getting
const bad = { '{"title":"some title", "body":"some body", "createdBy":" "created By"}':''};
console.log(bad);
console.log(bad.title);
// This is what you should post
const good = {"title":"some title", "body":"some body", "createdBy":"created By"};
console.log(good);
console.log(good.title);
Update
You're sending form data, instead of a JSON payload.
use: 'Content-Type': 'application/json' instead of 'Content-Type': 'application/x-www-form-urlencoded'

POST event on outlook calendar using node.js : error InvalidAuthenticationToken

I am using this code to authenticate on Outlook Calendar (Oauth2) and then post an event to my calendar. I'm getting an error that after my first authentication the token is expired so O can't post on the calendar. If someone can help to find the error in my code :)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var moment = require('moment');
var querystring = require('querystring');
var outlook = require('node-outlook');
var microsoftGraph = require("#microsoft/microsoft-graph-client");
var currentToken;
var authHelper = require('./authHelper');
// 3- Configure express
// Set up rendering of static files
app.use(express.static('static'));
// Need JSON body parser for most API responses
app.use(bodyParser.json());
// Set up cookies and sessions to save tokens
app.use(cookieParser());
app.use(session(
{ secret: '************',
resave: false,
saveUninitialized: false
}));
// 4- Home page
app.get('/', function(req, res) {
res.write('<a id="signin-button" class="ms-Button ms-Button--primary"
href="'+authHelper.getAuthUrl()+ '"><span class="ms-Button-label">Click here
to sign in</span></a>');
res.end();
});
app.get('/authorize', function(req, res) {
var authCode = req.query.code;
if (authCode) {
console.log('');
console.log('Retrieved auth code in /authorize: ' + authCode);
authHelper.getTokenFromCode(authCode, tokenReceived, req, res);
}
else {
// 5- redirect to home
console.log('/authorize called without a code parameter, redirecting to
login');
res.redirect('/');
}
});
// 6- if it can't take the token
function tokenReceived(req, res, error, token) {
if (error) {
console.log('ERROR getting token:' + error);
res.send('ERROR getting token: ' + error);
}
else {
// 7- save tokens in session
req.session.access_token = token.token.access_token;
req.session.refresh_token = token.token.refresh_token;
req.session.email = authHelper.getEmailFromIdToken(token.token.id_token);
res.redirect('/logincomplete');
}
}
// 8- login complete
app.get('/logincomplete', function(req, res) {
var access_token = req.session.access_token;
var refresh_token = req.session.access_token;
var email = req.session.email;
currentToken = access_token;
var http = require("https");
var options = {
"method": "POST",
"hostname": "graph.microsoft.com",
"port": null,
"path": "/v1.0/me/events",
"headers": {
"authorization": "Bearer 'access_token'",
"content-type": "application/json",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write("{\n \"subject\": \"My M\",\n \"start\": {\n \"dateTime\":
\"2017-11-30T15:34:40.942Z\",\n \"timeZone\": \"UTC\"\n },\n \"end\":
{\n \"dateTime\": \"2017-12-07T15:34:40.942Z\",\n \"timeZone\":
\"UTC\"\n }\n}");
req.end();
});
// Start the server
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Make voice call using node js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

Resources