$.post($gameNetwork._serverURL+'/addfriend',
{username:"r",tusername:"w"}).done(function (data) {
console.log("finished");
});
Account.statics.
friend = function(name,tname,cb) {
return this.findOneAndUpdate(
{ 'username': name },
{ $push: {'friendlist': tname}},
{ upsert: true, new: true},
cb);
};
route
router.post('/addfriend', function(req, res) {
//Account.findByName(req.body.username, function(err, account){
Account.friend(req.body.username,req.body.tusername, function(err, account){
if (err) {
return res.status(203).json({
err: err.msg
});}
if (!account) {
return res.status(203).json({
err: "Invalid username"
});}
var tname = req.body.tusername;
var profile = {
tname : tname,
name: account.username,
email: account.email,
id: account._id,
rank: account.rank
}; });
this code should enter "w" in to the field 'friendlist' in Mongodb, but I got null instead of w.
how can I get "w" into the field 'friendlist' in Mongodb.
Any help is appreciated
Thanks in advance
router in an ExpressJS router?
If yes did you set the bodyParser middleware?
If not, set it like this
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/json
app.use(bodyParser.json())
You can also try to stringify the body in the ajax request like described here
You can debug your data of request like this:
router.post('/addfriend', function(req, res) {
console.log(req.body);
// your logic
}
Run your code again, and you can see your data that you expect. If you see tusername = null or undefined, may be the problem in configure of your module that you use, example body-parser, busboy...vv
All comments are welcome!
Related
I am wondering if anyone can help me out here. I'm currently taking a Udemy course on learning how to connect a database with my server. I have been going word by word on the teacher's code, frequently checking if my code has any minor errors. I didn't have any trouble with code thus far on my server.js file. Port is running smoothly. However, when I run the POST request from Postman, I get
Unhandled rejection Error: Connection terminated unexpectedly
Through Postman, I am following exactly what the teacher did. The POST request contains email, password, name and the localhost:3000/register path is fine. That is what my server is connected to. I'm wondering what's going on since my code runs smoothly until I do a POST request. Also noting that I get 200 OK response on Postman but on server, I get that unhandled rejection error message.
Yeah that console log is intentional, I am going along exactly what he is doing in the video so code is bound to change over time on the next video.
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require ('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const pg = require('pg');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
port: '3000',
password : '',
database : 'smart-brain'
}
});
const app = express();
const database = {
users: [
{
id: '123',
name: 'Jess',
email: 'jess#gmail.com',
password: 'cookies',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Sally',
email: 'sally#gmail.com',
password: 'bananas',
entries: 0,
joined: new Date()
}
]
}
app.use(bodyParser.json());
//body parser is basically json.parse. we want to always parse json so our code is readable in string form. POST > Raw > JSON
app.use(cors())
app.get('/', (req, res)=> {
res.send(database.users);
})
app.post('/signin', (req, res) => {
if(req.body.email === database.users[0].email && req.body.password === database.users[0].password) {
res.json(database.users[0])
} else {
res.status(400).json('error logging in')
}
})
app.post('/register', (req, res) => {
const { email, name, password } = req.body;
db('users').insert({
email: email,
name: name,
joined: new Date()
}).then(() => console.log())
res.json(database.users[database.users.length-1])
});
app.get('/profile/:id', (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
return res.json(user);
}
})
if (!found) {
res.status(400).json('not found...')
}
})
//now we are creating route for entries count. everytime they submit image, they will get a count for it
app.put('/image', (req, res) => {
const { id } = req.body;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
user.entries++
return res.json(user.entries);
}
})
if (!found) {
res.status(400).json('not found...')
}
})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
try to add catch function after then block.
app.post('/register', (req, res) => {
const { email, name, password } = req.body;
db('users').insert({
email: email,
name: name,
joined: new Date()
}).then(() => {
res.json(database.users[database.users.length-1])
}).catch((err)=>{console.log(err)})
});
Hi so I have been using this node server for some time and it recently stopped working (presumably due to some logical error I mistakenly adjusted), throwing a 404 when I run the server. When I call on it with an http request it throws a 404 as well and shows the same on load from the actual URL in a browser. What is going on?
ter image description here]3]3
index.js:
//Environment Vars
var uri = process.env.NODE_ENV || "development"
console.log(uri + " environment")
//Express App
var express = require('express');
var app = express();
//Api for reading http post request body in express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
//Log Connections
app.use(function timeLog (req, res, next) {
console.log('incoming connection . . . ')
console.log(req)
next()
})
//API middelware
var api = require('./api')
app.use('/api', api)
app.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'Welcome!', success: true, error: null }));
});
//Create Server
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
console.log('Server running on port ' + port + '.');
});
api.js
var express = require('express')
var router = express.Router()
var stripe_key = process.env.STRIPE_KEY || "sk_test_P9XQtrrfGYU9mF8h6C47bgUp"
var stripe = require('stripe')(stripe_key);
var request = require("request-promise-native")
//API
router.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'API Gateway', success: true, error: null }));
}) // Just for testing, just for error-handling
//1. Create a customer account
router.post('/new_customer', function (req, res) {
console.log("Creating new customer account...")
var body = req.body
stripe.customers.create({ email: body.email, })
.then((customer) => {
console.log(customer)
// Send customerId -> Save this on Firebase for later use
res.status(200).send(JSON.stringify({ success: true, error: null, customerId: customer.id }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//2. Save Credit Card with token
router.post('/new_card', function (req, res) {
var customerId = req.body.customerId
var token = req.body.token
stripe.customers.update(customerId, { source: token })
.then((customer) => {
console.log(customer)
res.status(200).send(JSON.stringify({ success: true, error: null }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//3. Use customerId to post a charge
router.post('/new_charge', function (req, res) {
var customerId = req.body.customerId
var amount = req.body.amount
var source = req.body.source
stripe.charges.create({
amount: amount, //in cents
currency: "usd",
customer: customerId, //CUSTOMER_STRIPE_ACCOUNT_ID
source: source, // obtained with Stripe.js
}).then((charge) => {
res.status(200).send(JSON.stringify({ message: 'Sucess.', success: true, error: null }));
}).catch((error) =>{
res.status(400).send(JSON.stringify({ message: 'Error', success: false, error: error }));
})
})
router.post('/ephemeral_keys', (req, res) => {
const stripe_version = req.body.api_version;
var customerId = req.body.customerId;
if (!stripe_version) {
res.status(400).end();
return;
}
console.log(stripe_version)
// This function assumes that some previous middleware has determined the
// correct customerId for the session and saved it on the request object.
stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: stripe_version}
).then((key) => {
console.log("Ephemeral key: " + key)
res.status(200).json(key);
res.status(200).send(JSON.stringify({ message: 'AAAAhh', success: true, error: null }));
}).catch((err) => {
console.log("Ephemeral key error: " + err)
res.status(200).send(JSON.stringify({ message: 'ABBBBBB', success: true, error: null }));
res.status(500).end();
});
});
module.exports = router;
Other details:
Two important files: index.js & api.js but functionality is all in api.js which is why URL stem goes: .../api/...
Ok got the issue and its as silly as it can get. Are you sure you started the right server ? Its definitely not the node server. Its the http-server you have started. To start the server through node you need to go into the directory (in the terminal) and write "node index.js". Necessary code to start a http-server is written inside index.js.
Got this from the below screenshot.
the error for me is that you are making a GET request on a route that requires a POST request:
router.post('/new_charge', function (req, res) {
...
})
So you should check that you are making a post request to this route and not a GET request. How are you accessing that route from the client?
There is no router.get route for '/api/new_charge', there is one router.post route though.
Where is your router.get('/new_charge') route? it's not in the files you posted. You might have either deleted it or the /new_charge route needs to be used as post and not get.
I want to preface this by saying I have read several posts here regarding this issue.
I have a node/express/mongo app with the following:
app.js:
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var morgan = require('morgan')
var mongoose = require('mongoose')
var passport = require('passport')
var app = express()
// MongoDB Setup
var configDB = require('./config/database.js')
mongoose.connect(configDB.url)
app.use(morgan('combined'))
app.use(bodyParser.json())
// Check security with this
app.use(cors())
// load our routes and pass in our app and fully configured passport
require('./routes')(app)
app.listen(process.env.PORT || 8081)
console.log('We are up and running, captain.')
routes.js
const AuthenticationController = require('./controllers/AuthenticationController')
module.exports = (app) => {
app.post('/register', AuthenticationController.register)
}
My mongo schema file Account.js:
const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const Schema = mongoose.Schema
var accountSchema = new Schema({
email: String,
password: String,
likesPerDay: { type: Number, min: 0, max: 250 },
followPerDay: { type: Number, min: 0, max: 250 },
unfollowPerDay: { type: Number, min: 0, max: 250 },
commentsPerDay: { type: Number, min: 0, max: 250 },
comment: String,
hashtags: [String]
})
// methods ======================
// generating a hash. We hash password within user model, before it saves to DB.
accountSchema.methods.generateHash = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
}
// checking if password is valid
accountSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.local.password)
}
// create the model for users and expose it to our app
module.exports = mongoose.model('Account', accountSchema)
And finally my controller file AuthenticationController.js
const Account = require('../models/Account.js')
// var bodyParser = require('body-parser')
module.exports = {
register (req, res) {
Account.findOne({email: req.body.id}, function (err, account) {
if (err) {
console.log('Could not regster user')
throw err
}
if (account) {
console.log('account already exists')
} else {
Account.insertOne({email: req.body.email, password: req.body.password}, function (err, res) {
if (err) {
console.log('could not insert')
throw err
}
console.log('inserted account')
Account.close()
})
}
})
}
}
I am getting an error in my AuthenticationController file when I call Account.insertOne function.
I get the error that
TypeError: Account.insertOne is not a function
Now several of the posts here on stack have advised that I make sure that I am exporting the model from my model class, which I am doing, and that would fix this issue. Its weird because the findOne method seems to be fine, but when I call the insertOne i get an issue.
Am I missing something here?
A Mongoose model doesn't have an insertOne method. Use the create method instead:
Account.create({email: req.body.email, password: req.body.password}, function (err, doc) {
The Mongoose docs show how to create documents:
Either via Account.create():
Account.create({email: req.body.email, password: req.body.password}, function (err, res) {
// ...
})
Or by instantiating and save()ing the account:
new Account({email: req.body.email, password: req.body.password}).save(function (err, res) {
// ...
})
edit
as of mongoose documentation, try using
Account.create({ ...params ... }, function (err, small) {
if (err) return handleError(err);
// saved!
})
insertOne command is not available in mongoose directly as mentioned in Mongoose Documentation. If you want to use insertOne command then you need to use bulk command in order to send this command to MongoDB server. Something like below. I hope this works.
Account.bulkWrite([
{
insertOne: {
document: {email: req.body.email, password: req.body.password}
}
}
}]
I'm trying to write/add data in a json file (for example for each request, a new json is added in the json file) i am using Express.js. I am new to all of this so I really don't know what to do. I'm using a POST request, here's what i got so far. I know it's a big catastrophic mess, i scraped everything that could help me and gathered all of it. I'm just SO lost. Thanks for your help !
app.post('*/', function(req, res) {
res={
first_name: req.body.first_name,
last_name: req.body.last_name,
reponse1: req.body.reponse1,
reponse2: req.body.reponse2,
};
JSON.stringify(res);
var body = {
table: []
};
body.table.push(res);
filePath = __dirname + '/data.json';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.appendFile(filePath, body, function() {
res.end();
});
});
});
In your code, I see a lot of bugs. Firstly, you should not assign res = { }. Secondly, you stringify the JSON data like below. I will also suggest you to go through some tutorials of Node.js first. You can go through https://www.tutorialspoint.com/nodejs/ or https://www.codementor.io/nodejs/tutorial.
For your requirement, you can simply use following code:
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const fs = require('fs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/', function(req, res){
var body = {
first_name: req.body.firstName,
last_name: req.body.lastName
}
filePath = __dirname + '/data.json'
fs.appendFile(filePath, JSON.stringify(body), function(err) {
if (err) { throw err }
res.status(200).json({
message: "File successfully written"
})
})
})
app.listen(3000,function(){
console.log("Working on port 3000")
})
I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("MongoDB connection is open.");
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
X: Number,
Y: Number,
Orientation: Number,
UserID: String,
Time: String
});
// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);
// create application/json parser
var jsonParser = bodyParser.json();
// URL management
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
console.log(req.body);
}
});
// Start the server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('App listening at %s:%s',host, port)
});
The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:
{
datapoint_1:
{ timestamp: '2015-02-06T13:02:40:361Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 271.3345946652066 },
datapoint_2:
{ timestamp: '2015-02-06T13:02:40:961Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 273.6719055175781 }
}
So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?
Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
for(var datapoint in req.body){
//create new instance of LocationCollection document
var point = new LocationsCollection({
X:Number(req.body[datapoint]["x"]),
Y:Number(req.body[datapoint]["y"]),
Orientation:Number(req.body[datapoint]["orientation"]),
Time:req.body[datapoint]["timestamp"],
UserID:req.body[datapoint]["id"]
});
//insert the newly constructed document into the database
point.save(function(err, point){
if(err) return console.error(err);
else console.dir(point);
});
}
}
});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
if(err) console.error(err);
else console.dir(data);
});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send({
error: 'BROKEN_JSON'
});
}
}}));
It should be a simple for (var key in obj) loop:
app.post('/update', jsonParser, function (req, res) {
var locationObject = req.body(),
insertObjects = [],
key;
for (key in locationObject) { // loop through each object and insert them into our array of object to insert.
insertObjects.push(locationObject[key]);
}
if (!insertObjects.length) { // if we don't have any object to insert we still return a 200, we just don't insert anything.
return res.status(200).send({
success: true,
message: 'Nothing inserted, 0 locations in POST body',
count: 0;
});
}
LocationsCollection.create(insertObjects, function (err, res) {
if (err) {
return res.status(400).send({
success: false,
message: err.message
});
}
// we have successfully inserted our objects. let's tell the client.
res.status(200).send({
success: true,
message: 'successfully inserted locations',
count: insertObjects.length;
});
});
});
Mongo allows for inserting multiple documents with a single callback, which makes this a lot easier.
This also checks the schema to ensure only proper documents are created.