i get error about Body-Parser when i post data with Postman on localhost:3000/send-data
, i thought it can get fixed with express.json() but it didn't, also what is the simplest way to post data to mongoDB with React-native?
here are my codes:
app.js :
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
require("./ads")
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
const Ads = mongoose.model("ads")
const mongoURI = *
mongoose.connect(mongoURI, {
useNewUrlParser : true,
useUnifiedTopology: true
})
mongoose.connection.on("connected",() => {
console.log("connected to server")
})
mongoose.connection.on("error",(err) => {
console.log("error",error)
})
app.post('/send-data',(req,res) => {
const ads = new Ads({
name : req.body.name,
title : req.body.title,
title2 : req.body.title2,
})
ads.save()
.then(data => {
console.log(data)
res.send("seccsudss")
}).catch(err => {
console.log(err)
})
})
app.get('/',(req,res) => {
res.send("welcome to nodejs")
})
app.listen(3000,() => {
console.log('listening on 3000')
})
and error i get is :
SyntaxError: Unexpected token } in JSON at position 185
at JSON.parse (<anonymous>)
at parse (/home/kian/project/project/project/node_modules/body-parser/lib/types/json.js:89:19)
at /home/kian/project/project/project/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/kian/project/project/project/node_modules/raw-body/index.js:224:16)
at done (/home/kian/project/project/project/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/kian/project/project/project/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:314:20)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
You can pass string as json keys
{
"name" : req.body.name,
"title" : req.body.title,
"title2" : req.body.title2
}
Related
I am trying to preview a JasperReports Server report through Axios, the problem is that when I run it (localhost:port) it keeps loading and does nothing, any help on this?
const express = require('express')
const axios = require("axios")
const app = express()
app.get('/', async function(req,res){
try {
const url = "http://localhost:8080/jasperserver/rest_v2/reports/Re013.pdf"
const params = {
AMB_OCULTO : "123",
AMB : "123",
INS : "FF",
ORD_INI: "419435",
ORD_FIN: "419435"
}
const file = await axios.get(url, {
params: params,
responseType: "stream",
auth:{
username: "jasperadmin",
password: "jasperadmin"
}
})
res.writeHead(200,{"Content-Type":"application/pdf"})
file.data.pipe(res)
} catch (error) {
console.log(error)
}
})
app.listen(4000,()=>{
console.log('')
})
In my API is the current user (I have logged in with passport) but when I make an Axios get request the data field is empty. I absolutely don't know what to do :(
<script>
import axios from "axios"
export default {
name: 'Home',
components: {
},
data: function() {
return {
user: axios.get('http://127.0.0.1:3000/api/').then(response => this.user = response)
}
},
methods: {
}
}
</script>
Here is the output:
Here is my API:
Edit: Here is my Backend File:
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const cors = require('cors')
const passport = require('passport')
let LocalStrategy = require('passport-local').Strategy;
const session = require('express-session')
var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const port = 3000
app.use(cors({
methods:['GET','POST'],
credentials: true
}))
app.use(express.static('public'))
//Passport setup
app.use(session({
secret: 'test',
resave: false,
saveUninitialized: false,
secure: true
}))
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
const apiRoutes = require('./apiRoutes')
app.use(cors())
app.use('/api', apiRoutes)
// connect to database
mongoose.connect('mongodb+srv://#cluster0.dhsiv.mongodb.net/test?retryWrites=true&w=majority',
{useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log('Erfolgreich connected')
})
app.listen(port, () => {
console.log('server is running on port '+port)
})
module.exports;
I hope someone can help me. Thanks a lot guys :)
i have also change my data and run the axios get in mounted but it doesnt change anything.
Routes:
const { _ } = require('core-js');
const { Mongoose } = require('mongoose');
const { find, where } = require('./models/userModel');
const userModel = require('./models/userModel');
let router = require('express').Router();
const bcrypt = require('bcryptjs')
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
let jwt = require('jsonwebtoken');
const { static } = require('express');
require('./passportConfig')
router.get("/", (req, res) => {
res.json({
user: req.user
});
});
I'm making a project for my college assignment, but I'm having a trouble while i'm trying to get a data from database called 'project' in 'sitelist' collection from MongoDB.
But for some reason the data i got is only an empty array [ ].
I'm new to MongoDB so i want to know where did i do wrong.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const SLDBModel = require('./sldb_schema');
require('./db');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }))
app.use(function (req, res, next)
{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers','content-type, x-access-token');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/api/getList', function (req, res){
SLDBModel.find({},function(err, data){
if(err){
console.log('//app.get// getList error!...');
res.send(err);
}
else{
console.log(data);
res.send(data.map(v => v.toJSON()));
}
});
});
module.exports = app;
app.listen(3000, ()=>{
console.log("SERVER IS ONLINE! ON PORT 3000");
})
sldb_schema.js
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SLSchema = new Schema({
S_NAME: {type: String, required: true},
S_ADD: {type: String, required: true},
S_STATUS: {type: String, required: true}
}
);
const SLDBSchema = new Schema({
list: [SLSchema]
}
);
const SLDBModel = mongoose.model('sitelist', SLDBSchema);
module.exports = SLDBModel;
db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/project', {useUnifiedTopology: true, useNewUrlParser: true });
mongoose.connection.on('connected', function () {
console.log('MONGOOSE default connection open');
});
mongoose.connection.on('error', function (err) {
console.log('MONGOOSE default connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('MONGOOSE default connection disconnected');
});
process.on('SIGINT', function () {
mongoose.connection.close(function ()
{
console.log('MONGOOSE default connection disconected through app termination');
process.exit(0);
});
});
Data in database called 'project' in collection 'sitelist'
{
"_id" : ObjectId("5ec4672e44f01dcae82c3dde"),
"error" : "0",
"num_rows" : 3,
"list" : [
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "GTRCASINO",
"S_ADD" : "gtrcasino.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "GTRBETCLUB",
"S_ADD" : "gtrbetclub.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "77UP",
"S_ADD" : "77up.bet.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "DATABET88",
"S_ADD" : "databet88.net",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "FAFA855",
"S_ADD" : "fafa855.com",
"S_STATUS" : "UP"
}
]
}
Because your collection's name is not pluralize. Please check answer in below link.
MongoDB and Mongoose: Cannot retrieve data
I am new in mongodb and currently following this article: https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1
I am using mongoDB atlas as a course suggested and also whitelist my IP in it as many answers suggested.
File: .env
ATLAS_URI=mongodb+srv://sagar:<mypass>#cluster0-2gcdi.gcp.mongodb.net/test?retryWrites=true&w=majority
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
user.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
routes:users.js
const router = require('express').Router();
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
currently its showing Error in console:
UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms
at new MongooseTimeoutError (C:\Users\sagar\OneDrive\Desktop\nodejs\mern-exercise-tracker\backend\node_modules\mongoose\lib\error\timeout.js:22:11)
I am also testing my api in postman where its showing:
Could not get any response
There was an error connecting to http://localhost:5000/users/add.
Error of my screenshot:
I connect GraphQL with MongoDB but result is null. Help me !
index.js file:
const { graphql } = require('graphql');
const { MongoClient } = require('mongodb');
const assert = require('assert');
const readline = require('readline');
const mySchema = require('./schema/main.js');
const rli = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const MONGO_URL = 'mongodb://127.0.0.1:27017/test';
MongoClient.connect(MONGO_URL, { useNewUrlParser: true }, (err, db) => {
assert.equal(null, err);
console.log('Connected to MongoDB server');
rli.question('Client Request: ', inputQuery => {
graphql(mySchema, inputQuery, {}, { db }).then(result => {
console.log('Server Answer: ', result.data);
db.close(() => rli.close());
});
});
});
main.js file:
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLInt
} = require('graphql');
const queryType = new GraphQLObjectType({
name: 'RootQuery',
fields: {
usersCount: {
type: GraphQLInt,
resolve: (_, args, { db }) => db.collection('users').count()
}
}
});
const mySchema = new GraphQLSchema({
query: queryType
});
module.exports = mySchema;
And this is result:
Connected to MongoDB server
Client Request: { usersCount }
Server Answer: { usersCount: null }
From what i could understand the db object you get from MongoClient connect callback is not your db object but instead the client object so
you should first call
const db = client.db
see Connect to MongoDB
this is something that you can find and fix easily if you can debug your code