mailchimp sends response at Status:404 - javascript

I tried mailchimp API to create a mailing list for newsletter but the response I'm getting is 404
I don't understand I checked everything again and again but still it showing 404
maybe the endpoint is incorrect but I got that from their documentation
endpoint: https://us7.api.mailchimp.com/3.0/
I already changed my server to us7 as API says
API: de5bbb37311bd90fe9264e991bc7c83f-us7
list id: 81937afd8f
[
const express = require("express");
const https = require("https");
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 fname = req.body.firstname;
var lname = req.body.lastname;
var email = req.body.email;
const data = {
memebrs: [
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: fname,
LNAME: lname,
}
}
]
}
const jsondata = JSON.stringify(data);
const url = "https://us7.api.mailchimp.com/3.0/81937afd8f";
const options = {
meathod: "POST",
auth: "rootacess3000:de5bbb37311bd90fe9264e991bc7c83f-us7"
}
const request = https.request(url,options,function(response){
response.on("data", function(data){
console.log(JSON.parse(data));
})
})
request.write(jsondata);
request.end();
});
app.listen(3000, function() {
console.log("sever is running on port 3000");
});
]1

okay so here's the correction:
your url = "https://us7.api.mailchimp.com/3.0/81937afd8f"; is wrong it should be url = "https://us7.api.mailchimp.com/3.0/lists/81937afd8f";
There's a typo in spelling of method, it's not "meathod" it's "method"

Related

React node js contact form error 404 in production

I've made a contact form for my react app that works on localhost but once I deploy it doesn't work anymore. Been trying different url for post, with or without port but each time it throws an error.
As it is now I get this in the console:
Error: Request failed with status code 404 at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.x (xhr.js:66)
This is how I submit the mail:
axios({
method: 'POST',
url: 'https://url.com/send',
data: formData
}).then((response) => {
if (response.data.status === 'success') {
toast.success(
<div>
Success
</div>
);
resetForm();
} else if (response.data.status === 'fail') {
toast.error(
<div>
Error
</div>
);
}
});
This is my server:
var express = require('express');
var cors = require('cors');
var router = express.Router();
var nodemailer = require('nodemailer');
app.use(express.static('build'));
app.get('*', (req, res) => {
req.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
var transport = {
service: 'gmail',
auth: {
user: 'my_email#gmail.com',
pass: 'my_password'
}
};
var transporter = nodemailer.createTransport(transport);
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/send', (req, res, next) => {
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var phoneNumber = req.body.phoneNumber;
var subject = req.body.subject;
var message = req.body.message;
var dataConsent = req.body.dataConsent;
var content = `Name:\n${
firstName + ' ' + lastName
}\n\n\nEmail:\n${email}\n\n\nPhone Number:\n${phoneNumber}\n\n\nSubject:\n${subject}\n\n\nMessage:\n${message}\n\n\nConsent:\n${dataConsent}`;
var mail = {
from: email,
to: 'test#gmail.com',
subject: subject,
text: content
};
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
});
} else {
res.json({
status: 'success'
});
}
});
});
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', router);
app.listen(3002);
And in package.json I run this script on start:
"start": "node src/server.js",
var express = require('express');
const app = express(); // app comes after express require
var cors = require('cors');
var router = express.Router();
var nodemailer = require('nodemailer');
app.use(express.static('build'));
app.get('*', (req, res) => {
req.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
var transport = {
service: 'gmail',
auth: {
user: 'my_email#gmail.com',
pass: 'my_password',
},
};
var transporter = nodemailer.createTransport(transport);
transporter.verify((error, success) => {
if (error) {
console.log(error.message);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/contact',async (req, res, next) => {
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var phoneNumber = req.body.phoneNumber;
var subject = req.body.subject;
var message = req.body.message;
var dataConsent = req.body.dataConsent;
var content = `Name:\n${
firstName + ' ' + lastName
}\n\n\nEmail:\n${email}\n\n\nPhone Number:\n${phoneNumber}\n\n\nSubject:\n${subject}\n\n\nMessage:\n${message}\n\n\nConsent:\n${dataConsent}`;
var mail = {
from: email,
to: 'test#gmail.com',
subject: subject,
text: content,
};
const info = await transporter.sendMail(mail);
return res.send({info});
});
// const app = express(); app is executed in wrong place
app.use(cors());
app.use(express.json());
app.use('/', router);
app.listen(3002);
You have made mistakes this file. const app = express(); comes after var express = require('express');

How to print out jwt token

I am trying to generate a jwt token and print it out by calling res.json() after the user has been authenticated, the problem is that I get the following error:
Cannot set headers after they are sent to the client
I tried solving the issue by using async and await but it still gives me the error. How can I res.json my token successfully?
Here is my node.js server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const BASE_URL = process.env.BASE_URL;
const PORT = process.env.PORT || 1337;
const jwt = require('jsonwebtoken');
let Post = require('./models/post.model.js');
app.use(cors());
app.use("/assets", express.static(__dirname + "/assets"));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(BASE_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
app.set('view-engine', 'ejs');
app.get('/', (req, res) => {
res.render('index.ejs');
});
app.post('/', (req, res) => {
let username = req.body.username;
let password = req.body.password;
if (username !== process.env.USER_NAME && password !== process.env.USER_PASSWORD) {
res.json('Invalid credentials');
} else {
const token = jwt.sign({
username: username,
password: password
}, process.env.SECRET_KEY, {
expiresIn: '1h'
});
res.redirect('/dashboard');
res.json(token);
}
});
app.get('/dashboard', (req, res) => {
res.render('dashboard.ejs');
});
app.get('/dashboard/createPost', (req, res) => {
res.render('post.ejs');
});
app.post('/dashboard/createPost', async (req, res) => {
let collection = connection.collection(process.env.POSTS_WITH_TAGS);
res.setHeader('Content-Type', 'application/json');
let post = new Post(req.body);
collection.insertOne(post)
.then(post => {
res.redirect('/dashboard')
})
.catch(err => {
res.status(400).send(err);
});
});
app.listen(PORT);
You are calling res.redirect('/dashboard'); before the res.json(token);, you can't send a response twice that's why it's giving you the Cannot set headers after they are sent error.
What you can do instead is sending the token as a query via the redirect like this:
res.redirect(`/dashboard?token=${token}`);
Then you can get the token value from the front-end app by checking the query value.
Although this is not a very safe method

Express request doesn't end

i made a very simple api using express.js. Here's the code:
var express = require('express');
var app = express();
var morgan = require('morgan');
var UserModel = require('../Models/User')
app.use(morgan('short'));
app.use(express.json());
app.get('/getAll', (req, res) => {
res.status(200).json({auth: true});
})
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).end({auth: false})
res.status(200).end({user});
});
});
module.exports = app;
And here's the userModel:
const mongoose = require("mongoose")
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: false}
);
mongoose.model("User", UserSchema);
module.exports = mongoose.model("User");
This is the main server.js file:
var express = require('express');
var app = express();
const AuthController = require("./Controllers/AuthController");
const PORT = 3001;
app.use("/api/auth", AuthController);
app.listen(PORT, () => console.log(`Listening on port ${PORT}..`))
This is the db.js file:
const mongoose = require('mongoose');
const dbRoute = "mongodb://<user>:<password>#<stuff>/nodejs-db";
mongoose.connect(
dbRoute,
{useNewUrlParser: true}
);
So here's the problem. when i try to make a request to this api using Insomnia, the requests doesn't end. Basically Insomia starts sending the request and i have to wait like 20 secs until i get something on my express terminal. If i end the request manually i get this:
::ffff:127.0.0.1 - POST /api/auth/addUser HTTP/1.1 - - - - ms
I tried looking online but couldn't find anything useful.
I come from a django backgrond. I'm new to Node and Express js.
Edit:
The problem is only with the posts requests because whenever i make a get request it returns immediately {auth: true}.
Change your .end() to .send()
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).send({auth: false})
res.status(200).send({user});
});
});
I solved this problem.
Apparently the problem was that my db connection was on another file.
All i did was to move the content from the db.js file to my server.js file.
I forgot to include my db file.

Unable to read body in post response [express.js]

I am making a post request using Restlet client tool in chrome. In console.log(res), I can clearly see that there is body present there with totally correct data but still I am always getting an error message saying body is undefined when doing res.body.
Here is the code
var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(parser.urlencoded({extended: true}));
app.use(parser.json());
var db = mongoose.connection;
var port = process.env.PORT || 8000;
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/',function(req,res){
res.json({msg: 'Welcome to Pre-Health API!'});
});
var User = mongoose.Schema({
first_name: String,
last_name: String
},{
collection: 'User',
timestamps: true
});
router.route('/user').post(function(res,req) {
var user = mongoose.model('user',User);
console.log(req);
var new_user = new user({
first_name: req.body.first_name,
last_name: req.body.last_name
});
user.save(function(err) {
if(err) res.send(err);
res.json({message: "User created"});
});
});
app.use('/api',router);
app.listen(port);
console.log('API Listening on port: ' + port);
In the function you have req and res inverted, it should be:
router.route('/user').post(function(req, res) { ...

Cannot read property 'username' of undefined for Angular Post Request

From a tutorial I set up my app to post to my endpoint on the click of a button in angularjs. In the tutorial it works, but for me it doesn't work.
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
Is the problem line
serverapp.js
// LOAD ---- ---- ---- ----
var fs = require('fs');
var https = require('https');
var HTTPS_PORT = process.env.PORT || 3111;
var port = process.env.PORT || 3000;
var express = require('express');
var bodyParser = require('body-parser');
var Sequelize = require('sequelize');
var epilogue = require('epilogue');
var app = express();
var router = express.Router();
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var expressJwt = require('express-jwt'); //https://npmjs.org/package/express-jwt
var secret = 'this is the secret secret secret 12356';
var jwt = require('jsonwebtoken'); //https://npmjs.org/package/node-jsonwebtoken
// We are going to protect /api routes with JWT
app.use('/api', expressJwt({
secret: secret
}));
app.use('/', express.static(__dirname + '/'));
// if there's ever an unauth error, we redirect them
app.use(function(err, req, res, next) {
if (err.constructor.name === 'UnauthorizedError') {
res.status(401).send('Unauthorized :(');
}
});
app.post('/authenticate', function (req, res) {
//TODO validate req.body.username and req.body.password
//if is invalid, return 401
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
res.status(401).send('Wrong user or password');
return;
}
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john#doe.com',
id: 123
};
// We are sending the profile inside the token
var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });
res.json({ token: token });
});
// ...MODELS, relations, rest endpoints and all that crap withheld from stack overflow
app.get('/api/restricted', function(req, res) {
console.log('user ' + req.body.username + ' is calling /api/restricted');
res.json({
name: 'foo'
});
});
clientapp.js
myApp.controller('userController', function ($scope, $http, $window) {
$scope.user = {username: 'thisshouldbeempty', password: 'thisshouldbeempty'};
$scope.isAuthenticated = false;
$scope.welcome = '';
$scope.message = '';
$scope.loginUser = function () {
$http
.post('/authenticate', $scope.user)
.success(function (data, status, headers, config) {
$window.sessionStorage.token = data.token;
$scope.isAuthenticated = true;
var encodedProfile = data.token.split('.')[1];
var profile = JSON.parse(url_base64_decode(encodedProfile));
$scope.welcome = 'Welcome ' + profile.first_name + ' ' + profile.last_name;
})
// etc....
html partial, login is invoked via button press
<button class="btn waves-effect waves-light" ng-click="loginUser()">Submit
<i class="material-icons right">send</i>
</button>
You must use bodyParser to access req.body:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
See http://expressjs.com/en/api.html
As per the comment in the code:
//TODO validate req.body.username and req.body.password
The code is lacking validation of input. You are getting the error Cannot read property 'username' of undefined for Angular Post Request because 'username' is undefined.
You need to check that the user has provided the inputs required for the post request, i.e.
if(!req.body.username || !req.body.password)
return; // should probably return some sort of error code
Elaboration: 'should probably return some sort of error code': send a JSON response with error code 404 and a relevant error message such as "No username specified." and "No password specified."
e.g.
if(!req.body.username) {
res.status(404).send('No username specified');
return;
}
if(!req.body.password) {
res.status(404).send('No password specified');
return;
}

Categories