I am getting an error when submitting my newsletter app using NodeJs. I can't even add the dummy data. I am still learning and appreciate if you can send any reference for my concern.
Please see code below
const express = require("express");
const request = require("request");
const bodyParser = require("body-parser");
const https = require("https");
const path = require("path");
const sdk = require('api')('#activecampaign/v3#19qi536gl58csf5q');
const app = express();
const port = process.env.PORT || 3000;
//BodyParser MiddleWare
app.use(bodyParser.urlencoded({ extended:true}));
//Static Folder
app.use(express.static(path.join(__dirname, "public")));
//sending the signup.html file to the browser as soon as a request is made on localhost port#
app.get("/", (req,res)=>{
res.sendFile(__dirname + "/signup.html");
});
app.post("/", (req,res) => {
const firstName = req.body.fName;
const lastName = req.body.lName;
const email = req.body.email;
const baseUrl = "https://radmik1435080.api-us1.com/api/3/contacts";
const apiKey = "x";
const sdk = require('api')('#activecampaign/v3#19qi536gl58csf5q');
const data = sdk['create-a-new-contact']({
contact: {
email: 'johndoe#example.com',
firstName: 'John',
lastName: 'Doe',
phone: '7223224241',
fieldValues: [
{
field: '1',
value: 'The Value for First Field'
},
{field: '6', value: '2008-01-20'}
]
}
}, {
'Api-Token': 'x'
})
.then(res => console.log(res))
.catch(err => console.error(err));
});
app.post("/err", (req,res) => {
res.redirect("/");
})
app.listen(port, ()=>{
console.log(`Server running on port ${port} `);
});
This is the error message
https://pastebin.com/yAHk6Qsp
Thanks in advance.
Related
I'm new in couchbase and I'm using ottoman framework. I connected the database using ottoman and I create the schema and model User and exported it into controller file. When I create a new instance for that model, ottoman throw an error TypeError: User is not a constructor.
I search so many time and I red the official and non official documents and test it severely. I wrote all about the db in separate file and no change. I'll attach the file below it . But I didn't get any solution. please let me know...
const ottoman = require("ottoman");
exports.connect = async () => {
try {
await ottoman.connect({
connectionString: process.env.DB_CONNECTION_STRING,
bucketName: process.env.DB_BUCKET,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
console.log("Database connected.");
await ottoman.start();
} catch (error) {
console.log("Database not connected due to: ", error.message);
}
};
connect();
const User = ottoman.model("User", {
firstName: String,
lastName: String,
email: String,
tagline: String,
});
const perry = new User({
firstName: "Perry",
lastName: "Mason",
email: "perry.mason#example.com",
tagLine: "Who can we get on the case?",
});
const tom = new User({
firstName: "Major",
lastName: "Tom",
email: "major.tom#example.com",
tagLine: "Send me up a drink",
});
main = async () => {
await perry.save();
console.log(`success: user ${perry.firstName} added!`);
await tom.save();
console.log(`success: user ${tom.firstName} added!`);
};
main();
This issue happened due to disorder of functions calling in app.js file. All I used till now was a Mongodb and mongoose in noSQL. In the case of mongodb we can call the database config function after api endpoint specification. I wrote my code like this in couchbase. But it didn't stick in couchbase. I'll provide my code before and after fixing for more clarity, and I'm very sorry for my bad english. :)
Before fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// database setup
const db = require("./config/db");
db.connect();
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
After fixing app.js file:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 3000;
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// database setup
const db = require("./config/db");
db.connect();
// routes
app.use("/api/", require("./routes/index"));
// bad requiest
app.use("*", (req, res) => {
res.status(404).json({ message: "Bad Requist." });
});
// error middleware
const { errorHandler } = require("./middlewares/error-middleware");
app.use(errorHandler);
// server setup
app.listen(PORT, (err) => {
if (err) {
console.log(err.message);
} else {
console.log(`The server is running on: ${PORT}.`);
}
});
i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);
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.");
});
I am able to store data in my mongoDB database using req.body in a POST request but I am not able to retrieve that data using req.body in a GET request. I can retrieve data if I pass a string but not req.body..
I have seen there are multiple posts on this issue in which body parser seems to solve the issue but I am still retrieving undefined even though I have body parser going.
Thanks in advance.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 2000;
// app.use(express.urlencoded({extended: true}));
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(express.json());
app.use(bodyParser.json());
app.use(express.static('public'));
const database = mongoose.connect('mongodb://localhost/users')
.then(() => console.log('connected to mongoDB!!'))
.catch((err) => console.error('unable to connect', err));
const userSchema = {
name: String,
email: String
}
const User = mongoose.model('User', userSchema);
app.post('/api/users',(req,res) => {
const user = new User({
name: req.body.name,
email: req.body.email
});
const create = user.save();
res.send('created a user account');
});
app.get('/api/users', async (req,res) => {
const find = await User
.find({ name: req.body.name});
console.log(find);
res.send(`your data is ${req.body.name}`);
})
app.listen(PORT, () => console.log(`listening on port ${PORT}`));
GET Resquest doesn't have a body. Instead you need to use query parameters.
You can do something like:
app.get('/api/users', async (req,res) => {
const find = await User
.find({ name: req.query.name});
console.log(find);
res.send(`your data is ${req.query.name}`);
})
To complement Leandro Lima's answer,
for route parameters:
app.get('/api/users/:name', async (req,res) => {
const find = await User
.find({ name: req.params.name});
console.log(find);
res.send(`your data is ${req.params.name}`);
})
The .../:name part makes up req.params.name (for example, .../:id then is req.params.id).
And for query parameters: /api/users/Dave?sex=male&developer=yes
Then req.queryhas {sex: 'male', developer: 'yes'}, thus could use req.query.sex and req.query.developer as you see fit.
Check out this question too: Node.js: Difference between req.query[] and req.params
I am trying to build a reactjs app and I am trying to pass data through from my front end (react) to my backend (node/express). However I am getting an error when I try and view the page I get this error. (Cannot GET /home).
const express = require("express");
const app = express();
const port = 5000;
const cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true
})
);
app.post("/home", (req, res) => {
const data = [(generalDetail = req.body.generalDetail)];
console.log(generalDetail, "has been added to /home");
res.json(data);
});
app.listen(port, () => `Server running on port ${port}`);
here is my onSubmit function:
onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
You dont have a get route for home, that is why you are having trouble.
Add the following code above your post route.
app.get("/home", (req, res) => {
console.log("here");
});