Can't post to mongo/express api - angularjs

I'm trying to add to my mongodb database through my angular 2 frontend but It doesn't seem that the post is going through. I use morgan to log all requests and it shows nothing, then I don't see anything in my database.
my api route:
// add venue
router.post('/add_venue', (req, res, next) => {
let newVenue = new Venue({
_id: req.body._id,
name: req.body.name,
street: req.body.street,
city: req.body.city,
state:req.body.state,
zipcode:req.body.zipcode,
busy:req.body.busy
});
Venue.addVenue(newVenue, (err, venue) => {
if(err){
res.json({success: false, msg:'Failed to add venue'});
} else {
res.json({success: true, msg:'User registered'});
}
});
});
router.get('/venue/:id', (req, res, next) =>{
let venueID = req.params.id;
Venue.findById(venueID, (err, user) => {
if(err) throw err;
if(!venueID){
return res.json({success: false, msg: 'Venue not found'});
}
I haven't tried the get request yet. Here my model:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
const VenueSchema = mongoose.Schema({
_id:{
type:String,
required:true
},
name:{
type:String,
required:true
},
street:{
type:String,
required:true
},
city:{
type:String,
required:true
},
state:{
type:String,
required:true
},
zipcode:{
type:String,
required:true
},
busy:{
type:Boolean,
},
});
const Venue = module.exports = mongoose.model('Venues', VenueSchema);
module.exports.addVenue = function(newVenue, callback){
newVenue.save(callback);
}
and here's the service i'm using on the front-end. I'm getting no errors with angular 2, it's all just through the back-end.
#Injectable()
export class VenueService{
constructor(private http:Http){
}
getVenue(id){
var headers = new Headers();
return this.http.get('//ec2 instance/venues/venues'+ id)
.map(res => res.json());
}
addV
enue(newVenue){
var headers = new Headers;
headers.append('Content-Type', 'application/json');
return this.http.post('(I'm using an ec2 address)/venues/venues', newVenue, {headers:headers})
.map(res => res.json());
}}
I'm using vscode, and I'm fairly new to javascript. Is there something I missed here?

Try using following way
JS
var newVenue = {
data: 'something'
};
$http.post('http://url/data', newVenue, {
headers: headers
})
.then(res => console.log(res.data());
This way you can see what is coming response or test your rest apis/calls from Postman rest client app

Related

Res.json not sending data in React app and appearing as undefined

I am developing a React with Nodejs backend and I have implemented "stripe" in order to process payments. The problem appears when I need to get the URL which should redirect me to the Stripe payment form. I should get it from a json response, but it is empty, no matter what I send. I've even tried sending really simple data, but it still doesn't work. I've used it before without problems in this project, so I don't know what I am doing wrong here. Can anyone offer any help? Thank you!
This is the router file, which creats the session for the payment and which is also supposed to send the needed URL. I tested and the URL is correct, it is just a matter of sending it through res.json
router.post("/payment", async(req, res) => {
const course = await Courses.findByPk(req.body.items[0].id);
const storeItems = new Map([
[course.id, { priceInCents: course.price, name: course.title }],
])
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
line_items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
price_data: {
currency: "usd",
product_data: {
name: storeItem.name,
},
unit_amount: storeItem.priceInCents,
},
quantity: item.quantity,
}
}),
success_url: 'http://localhost:3000/profile-page',
cancel_url: `http://localhost:3000/course-details/${course.id}`
})
res.json({ url: session.url });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
And this is where I should be getting the URL back, but I don't. Instead, when I console.log it, I get "undefined".
if (response.data.error) {
alert(response.data.error);
} else {
axios.post("http://localhost:3001/users_courses/payment", {
items: [
{ id: data.id, quantity: 1 },
],
}, {
headers: {
accessToken: localStorage.getItem("accessToken"),
},
}).then(res => {
if(res.ok) return res.json();
return res.json().then(json => Promise.reject(json));
}).then (( { url }) => {
window.location.href = url;
console.log(url + " this is the url");
}).catch(e => {
console.error(e.error);
})
}
I think it has to do with how you’re handling your axios post, I think with a small change like I suggested below this should work for you.
axios
.post(
"http://localhost:3001/users_courses/payment",
{
items: [{ id: response.data.id, quantity: 1 }],
},
{
headers: {
accessToken: localStorage.getItem("accessToken"),
},
}
)
.then(({ data: { url } }) => {
window.location.replace(url);
console.log(url + " this is the url");
})
.catch((e) => {
console.error(e.error);
});
Note that axios is not like the fetch API where you have to handle the transformation of the response body into the json object.

How find error authentication passport and react?

I have also error with passportjs. Before errors if you know good tutorial passportjs, passport-local-mongoose with react please send me link.
I watch a video youtube and work code in [that][1] . This is github. But I want change authentication passport. In modaljs I do this:
const mongoose = require('mongoose');
const moment = require("moment");
const passportLocalMongoose = require('passport-local-mongoose');
const userSchema = mongoose.Schema({
name: {
type:String,
maxlength:50
},
email: {
type:String,
trim:true,
unique: 1
},
password: {
type: String,
minglength: 5
},
lastname: {
type:String,
maxlength: 50
},
role : {
type:Number,
default: 0
},
image: String
});
userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});
const User = mongoose.model( 'User' , userSchema );
module.exports = {User};
in Userjs I do this:
const { User } = require('../models/model');
const router = require('express').Router();
const passport = require('passport');
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser( async function(id, done) {
await User.findById(id, function(err, user) {
done(err, user);
});
});
router.get('/auth', (req, res) => {
// res.send(req.isAuthenticated)
if(req.isAuthenticated()){
res.status(200).json({
_id: req.user._id,
isAdmin: req.user.role === 0 ? false : true,
isAuth: true,
email: req.user.email,
name: req.user.name,
lastname: req.user.lastname,
role: req.user.role,
image: req.user.image,
});
}
else{
return res.json({
isAuth: false,
error: true
});
}
});
router.post('/register', async (req, res) => {
await User.register( {email: req.body.email}, req.body.password, (err,user)=>{
if(err) return res.json({ success: false, err });
else res.status(200).json({
success: true
});
});
});
router.post("/login", function (req, res) {
console.log(req.body);
passport.authenticate("local")(req, res, function () {
console.log("ok!");
res.json({
loginSuccess: false,
message: "Invalid email or password"
});
});
});
router.get('/logout', (req, res) => {
if(req.isAuthenticated){
req.logout();
res.status(200).send({
success: true
});
}
else return res.json({success: false});
});
module.exports = router;
in server.js I add passport and this:
app.use(passport.initialize());
app.use(passport.session());
When first time I start server I get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
But after I get nothink. only show console req.body. How find error. I am very tired with passportjs. Where I find best tutorial passportjs with plugin database in passport-local-mongoose. And How find error and fix it. Sorry my english:))
[1]: https://github.com/jaewonhimnae/boilerplate-mern-stack
Please try res.status(200).send instead of res.status(200).json

When creating a MERN application, I need to create a POST request from frontend to the backend, but the request body is empty

I am creating a MERN application, where I am trying to send a post request to my backend, however when i log the req.body from my backend, it is empty
const removeTour = (id) => {
const getDevices = async () => {
const settings = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'here', info: '1', image: '1', price: '1' })
};
try {
const fetchResponse = await fetch(`http://localhost:3080/add-tour`, settings);
const data = await fetchResponse.json();
return data;
} catch (e) {
return e;
}
};
getDevices();
const newTours = tours.filter((tour) => tour._id !== id);
setTours(newTours);
};
The function is called when the button is pressed.
On the backend, i have an app.post, which should receive the request. THe request.body received is empty
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const data = require('./data.json');
//dotenvs
const DBLink = process.env.DB_HOST;
const port = process.env.PORT;
const home = process.env.HOME;
//app
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
//shema
const TourSchema = mongoose.Schema({
name: {
type: String,
required: true
},
info: {
type: String
// required: true
},
image: {
type: String
// required: true
},
price: {
type: String
// required: true
}
});
const Tour = mongoose.model('tour', TourSchema);
//app routes
app.get('/', (req, res) => {
(async () => {
const tours = await Tour.find((data) => data);
try {
res.json(tours);
} catch (error) {
console.log(error);
}
})();
});
app.post('/add-tour', (req, res) => {
console.log(req.body);
// const { name, image, info, price } = req.body;
// const tour = new Tour({ name, image, info, price });
// tour.save();
// res.status(201).redirect('http://localhost:3000/');
res.send('here');
});
//mongoose
mongoose
.connect(DBLink, {
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => {
app.listen(port, () => console.log(`Server is running on ${port}`));
})
.catch((err) => console.log(err));
All i get in the terminal is -
terminal:
{}
However when i am making a post request from a html form, with input that has a value and a name, the received request has the body
You probably have some issue applying body-parser. Check following official example https://github.com/expressjs/body-parser "Express/Connect top-level generic". If you add app.use(bodyParser.json()) it should parse json correctly.

why when I use axios to post data to my mongodb cloud I got an object with _id and empty fields?

I made a react app and I can read data by axios.get() and I can delete data as well in the app, but the problem is I can't post data to my MongoDB cloud? any help, please.
I made a MongoDB cloud database as shown here.
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
mongoose.connect("mongodb+srv://Admin-Ali:AAssppmm11#cluster0.d0joo.gcp.mongodb.net/visualizor", { useNewUrlParser: true, useUnifiedTopology: true });
var Schema = mongoose.Schema;
var ArticaleSchema = new Schema({ title: String, tags: String }, { strict: false })
var Articale = mongoose.model("Article", ArticaleSchema);
// const articals = new Articale({ title: "title", tag: "h1" })
// articals.save();
//1. get Fetch all articals
app.get("/articals", (req, res) => {
Articale.find((err, foundArticals) => {
res.send(err ? err : foundArticals)
})
})
//2. post (Create One new Artical.)
app.post("/articals", (req, res) => {
new Articale(req.body).save((err) => { res.send(err ? err : req.body) })
})
//3.delete all the articals.
app.delete("/articals", (req, res) => {
Articale.deleteMany((err) => {
res.send(req.body);
})
})
app.route("/articals/:articleTitle")
.get((req, res) => {
Articale.findOne({ title: req.params.articleTitle },
(err, foundArticle) => { res.send(err ? err : foundArticle) })
})
.put((req, res) => {
Articale.update({ _id: req.params.articleTitle },
{ title: req.body.title }, { overwrite: true },
(err) => { res.send(err ? err : `${req.params.articleTitle}` + " Updated") })
})
.patch((req, res) => {
Articale.update({ _id: req.params.articleTitle }, { $set: req.body },
(err) => { res.send(err ? err : "Articale: " + `${req.params.articleTitle}` + " updatted") })
})
.delete((req, res) => {
Articale.deleteOne({ _id: req.params.articleTitle },
(err) => { res.send(err ? err : `${req.params.articleTitle}` + " Has deleted") })
})
app.listen(5000, function () {
console.log("Server started on: http://localhost:5000/");
});
then on other file
const api = axios.create({ baseURL: "http://localhost:5000/articals" })
api.post("/", { title: "update", tag: "h1" })
then I get
{
"_id": "5f2046a176af4d190018beea",
"__v": 0
}
Also when I use postman body, row and enter {title:"XX"
tag:"h1"} I got the same issue.
But when I use postman body, x-www-form-urlencoded and post data in it I got my data in the cloud without any problem?
Note: I use allow CORS access control chrome extension
const qs = require('querystring')
axios.post("/" , qs.stringify( { title: "update", tag: "h1" }), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
try this.

Axios > Express.router – Update(.put) method returning 404

I am trying to finish building the last CRUD method of my App. (C, R and D) all done. But updating seems to be proving bothersome. I have a function which combines the object ID with the new content to update with. I am getting Error: Request failed with status code 404printed to the console.
I think I'm failing to reach the database item using the ID.
Function which gathers the data and initiates the request
handleClick(e) {
e.preventDefault()
const data = {
id: this.props.sid, //someuniqueid
body: {
name: this.state.name, //foo
details: this.state.details, //bar
content: this.state.content, //baz
},
}
api
.updateSnippet(data)
.then(result => {
this.setState({
name: '',
details: '',
content: '',
message: `'${this.state.name}' has been created`,
})
setTimeout(() => {
this.setState({
message: null,
})
}, 2000)
console.log('UPDATE DATA SUCCESS!')
})
.catch(err => this.setState({ message: err.toString() }))
}
api.js - uses axios to fire the request (this may be where I am failing).
import axios from 'axios'
const service = axios.create({
baseURL:
process.env.NODE_ENV === 'production'
? '/api'
: 'http://localhost:5000/api',
withCredentials: true,
})
const errHandler = err => {
console.error(err)
if (err.response && err.response.data) {
console.error('API response', err.response.data)
throw err.response.data.message
}
throw err
}
export default {
service: service,
updateSnippet(data) {
console.log(data.id) //someuniqueid
console.log(data.body) //{name: "foo", details: "bar", content: "baz"}
return service
.put('/snippets' + data.id, {
data: data.body,
})
.then(res => res.data)
.catch(errHandler)
},
}
Snippet.js (schema)
const mongoose = require('mongoose')
const snippetSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'The snippet name is required'],
minlength: 1,
},
details: {
type: [String],
default: [],
},
content: {
type: String,
},
})
const Snippet = mongoose.model('Snippet', snippetSchema)
module.exports = Snippet
Relevant route in "routes/snippets.js" - This could also be where I am falling over
router.put('/', function(req, res) {
console.log(req.body)
Snippet.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content,
},
{ new: true },
function(err, response) {
if (err) {
console.log('we hit an error' + err)
res.json({
message: 'Database Update Failure',
})
}
console.log('This is the Response: ' + response)
}
)
})
You are sending the id in the url, so you need to parse it from req.params.id.
I also returned response.
routes/snippets.js
router.put("/:id", function(req, res) {
console.log(req.body);
Snippet.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
details: req.body.details,
content: req.body.content
},
{ new: true },
function(err, response) {
if (err) {
console.log("we hit an error" + err);
return res.json({
message: "Database Update Failure"
});
}
return res.send(response);
}
);
});
Also you need to update this line in api.js. Just add / after snippets
.put('/snippets' + data.id, { =>
.put('/snippets/' + data.id, {

Resources