API POST http://localhost:3000/[object%20Object] - javascript

I am making the payment app with stripe. (base on the stripe repo)
I made server.js with express.
When I clicked the pay button is clicked, console shows xhr.js:177 POST http://localhost:3000/[object%20Object] 404 (Not Found)
this error.
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, error => {
if (error) throw error;
console.log('server running on port' + port);
});
app.post('/pay', async (req, res) => {
if (req.method === 'POST') {
try {
const { amount } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
});
res.status(200).send(paymentIntent.client_secret);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
});
this is the checkout form
Checkoutform.js
import React, { useState } from 'react';
import { CardElement, useStripe, useElements } from '#stripe/react-stripe-js';
import BillingDetailsFields from './BillingDetailForm';
import axios from 'axios';
import styled from 'styled-components';
import payment_intents from './api/payment_intents';
const CheckoutForm = ({ price, onSuccessfulCheckout }) => {
const [isProcessing, setProcessingTo] = useState(false);
const [checkoutError, setCheckoutError] = useState();
const stripe = useStripe();
const elements = useElements();
const handleCardDetailsChange = ev => {
ev.error ? setCheckoutError(ev.error.message) : setCheckoutError();
};
const handleFormSubmit = async e => {
e.preventDefault();
const billingDetails = {
name: e.target.name.value,
email: e.target.email.value,
address: {
city: e.target.city.value,
line1: e.target.address.value,
state: e.target.state.value,
postal_code: e.target.zip.value,
},
};
setProcessingTo(true);
const cardElement = elements.getElement('card');
try {
const { data: clientSecret } = await axios.post(
{ payment_intents },
{
amount: price,
}
);
console.log(clientSecret);
const paymentMethodReq = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: billingDetails,
});
if (paymentMethodReq.error) {
setCheckoutError(paymentMethodReq.error.message);
setProcessingTo(false);
return;
}
const { error } = await stripe.confirmCardPayment(clientSecret, {
payment_method: paymentMethodReq.paymentMethod.id,
});
if (error) {
setCheckoutError(error.message);
setProcessingTo(false);
return;
}
onSuccessfulCheckout();
} catch (err) {
setCheckoutError(err.message);
}
};
const cardElementOpts = {
hidePostalCode: true,
};
return (
<form onSubmit={handleFormSubmit}>
<div>
<CheckoutTitle>Pay with</CheckoutTitle>
<BillingDetailsFields />
</div>
<div>
<CardElementContainer>
<CardElement
option={cardElementOpts}
onChange={handleCardDetailsChange}
/>
</CardElementContainer>
</div>
<div>
<PayBtn disabled={isProcessing || !stripe}>
{isProcessing ? 'Processing...' : `Confirm and Pay`}
</PayBtn>
</div>
</form>
);
};
I think there is an issue with the app.post('/pay', async (req, res) => {}
But I really don't know what is the problem.

Related

Socket io connection not established with express node js, console log does not work

Trying to connect to socket io through a separate chat page tab and not with index.html, but not able to connect. I do not want the chat page to be the home page. Server and client console log does not work either. This only console logs "Express app listening at http://localhost:8888" but not "New WS Connection".
Server.js
require('dotenv').config();
const express = require('express');
const querystring = require('querystring');
const axios = require('axios');
const port = 8888 || process.env.PORT;
const socketio = require('socket.io');
const cors = require('cors');
const path = require('path');
const http = require('http');
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(cors());
app.use(router);
io.on('connect', (socket) => {
socket.on('join', ({ name, room }, callback) => {
console.log('New WS Connection...');
const { error, user } = addUser({ id: socket.id, name, room });
if(error) return callback(error);
socket.join(user.room);
socket.emit('message', { user: 'admin', text: `${user.name}, welcome to room ${user.room}.`});
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined!` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });
callback();
});
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit('message', { user: user.name, text: message });
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
}
})
});
server.listen(port, function(){
console.log(`Express app listening at http://localhost:${port}`);
});
router.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('server is up and running');
});
module.exports = router;
chat.js on client side
import React, { useState, useEffect } from 'react'
import queryString from 'query-string';
import io from "socket.io-client";
import './Chat.css';
import InfoBar from '../InfoBar/InfoBar';
import Input from '../Input/Input';
import Messages from '../Messages/Messages';
import TextContainer from '../TextContainer/TextContainer';
let socket;
export default function Chat({ location }) {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [users, setUsers] = useState('');
const ENDPOINT = 'http://localhost:8888/';
useEffect(() => {
const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT);
console.log(name, room);
setName(name);
setRoom(room);
socket.emit('join', { name, room }, (error) => {
if(error) {
alert(error);
}
});
}, [ENDPOINT, location.search]);
useEffect(() => {
socket.on('message', (message) => {
setMessages(messages => [...messages, message]);
});
socket.on('roomData', ({ users }) => {
setUsers(users);
});
}, []);
const sendMessage = (event) => {
event.preventDefault();
if(message){
socket.emit('sendMessage', message, () => setMessage(''));
}
}
// console.log(message, messages);
return (
<div className="outerContainer">
<div className="container">
<InfoBar room={room}/>
<Messages messages={messages} name={name}/>
<Input message={message} setMessage={setMessage} sendMessage={sendMessage} />
</div>
<TextContainer users={users} />
</div>
);
}

"userdb validation failed: email: Path `email` is required."

Hello then i try to create new user i get error "message": "userdb validation failed: email: Path email is required."
cannot find there is a bad code field
controller.js
const { response } = require('express');
let Userdb = require('../model/model');
// create and save new user object
exports.create = (req, res) => {
// validate requast
if (!req.body) {
res.status(400).send({ message: 'Laukas negali būti tusčias!' });
return;
}
// new user
const user = new Userdb({
name: req.body.name,
email: req.body.email,
gender: req.body.gender,
status: req.body.status,
});
// save user to database
user
.save(user)
.then((data) => {
//res.send(data)
res.redirect('/add-user');
})
.catch((err) => {
res.status(500).send({
message: err.message || 'Kuriant kūrimo operaciją įvyko klaida',
});
});
};
// retrieve and ruturn all users
exports.find = (req, res) => {
Userdb.find();
if (req.query.id) {
const id = req.query.id;
Userdb.findById(id)
.then((data) => {
if (!data) {
res.status(404).send({ message: 'Nerastas naudotojas su id' + id });
} else {
res.send(data);
}
})
.catch((err) => {
res.status(500).send({ message: 'Error gaunant naudojo id' + id });
});
} else {
Userdb.find()
.then((user) => {
res.send(user);
})
.catch((err) => {
res
.status(500)
.send({
message:
err.message || 'Gaunant naudotojo informaciją įvyko klaida',
});
});
}
};
// update a new user by id
exports.update = (req, res) => {
if (!req.body) {
return res
.status(400)
.send({ message: 'Atnaujinant duomenis laukai negali būti tušti!' });
}
const id = req.params.id;
Userdb.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
.then((data) => {
if (!data) {
res
.status(404)
.send({
message: `Negalima atnaujinti naudotojo su ${id}.Naudotojas nerastas!`,
});
} else {
res.send(data);
}
})
.catch((err) => {
res.status(500).send({ message: 'Error atnaujinti nepavyko' });
});
};
// Delete a user with user id
exports.delete = (req, res) => {
const id = req.params.id;
Userdb.findByIdAndDelete(id)
.then((data) => {
if (!data) {
res
.status(404)
.send({ message: `Negalima ištrinti su id ${id}. Blogas id` });
} else {
res.send({
message: 'Naudotojas ištrintas!',
});
}
})
.catch((err) => {
res.status(500).send({
message: 'Negalima ištrinti naudotojo su id=' + id,
});
});
};
model.js;
const mongoose = require('mongoose');
let schema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
gender: String,
status: String,
});
const Userdb = mongoose.model('userdb', schema);
module.exports = Userdb;
router.js;
const express = require('express');
const route = express.Router();
const services = require('../services/render');
const controller = require('../controller/controller');
/**
* #description Root Route
* #method GET/
*/
route.get('/', services.homeRoutes);
/**
* #description add users
* #method GET/ add-user
*/
route.get('/add-user', services.add_user);
/**
* #description for update user
* #method GET/ update-user
*/
route.get('/update-user', services.update_user);
// API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);
module.exports = route;
render.js;
const axios = require('axios');
exports.homeRoutes = (req, res) => {
// Make a get request to api users
axios
.get('http://localhost:3000/api/users')
.then(function (response) {
res.render('index', { users: response.data });
})
.catch((err) => {
res.send(err);
});
};
exports.add_user = (req, res) => {
res.render('add_user');
};
exports.update_user = (req, res) => {
res.render('update_user');
};
connection.js;
const mongoose = require('mongoose');
const connectDB = async () => {
try {
//mongoDB connection string
const con = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(`MongoDB connected: ${con.connection.host}`);
} catch (err) {
console.log(err);
process.exit(1);
}
};
module.exports = connectDB;
server.js;
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require('body-parser');
const path = require('path');
const connectDB = require('./server/database/connection');
const app = express();
dotenv.config({ path: 'config.env' });
const PORT = process.env.PORT || 8080;
//log requests
app.use(morgan('tiny'));
// mongoDB connection
connectDB();
// parse request to body-parses
app.use(bodyparser.urlencoded({ extended: true }));
//set view engine
app.set('view engine', 'ejs');
//app.set("views",path.resolve(__dirname,"views/ejs"))
//load assets
app.use('/css', express.static(path.resolve(__dirname, 'assets/css')));
app.use('/img', express.static(path.resolve(__dirname, 'assets/img')));
app.use('/js', express.static(path.resolve(__dirname, 'assets/js')));
//css/style.css
//load routes
app.use('/', require('./server/routes/router'));
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
add this middleware app.use(bodyParser.json());
upper of app.use(bodyparser.urlencoded({extended:true}))
to get data from front

Using React.js, Node.js and Multer, how can I console log 'req.file' on the server?

I am building a MERN app and when I try to console.log(req.file) on the server I get undefined. I've checked the multer github page and other SO articles, but I still haven't been able to figure it out using React hooks and jsx. I'm newish to SO so, I will add edits since I can't comment yet.
Here is a link to the branch in GitHub if you want to see all the files. https://github.com/BenjDG/puzzle-gallery/tree/so
I'm new to multer and react so any help is appreciated.
Here is my code:
server\controllers\puzzleController.js
const multer = require('multer');
const upload = multer({ dest: './uploads'});
const db = require('../models');
const fs = require('fs');
const type = upload.single('picFile');
// Defining methods for the puzzleController
module.exports = {
findAll: function (req, res) {
db.Puzzle
.find(req.query)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
save: (type, function (req, res) {
// console.log(req);
console.log(req.file);
console.log(req.body);
res.sendStatus(200);
}),
remove: function (req, res) {
db.Puzzle
.findById({ _id: req.params.id })
.then(dbModel => dbModel.remove())
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
};
client\src\components\gallery\index.js
import React, { useState } from 'react';
import './styles.css';
import API from '../../services/API';
export default function Gallery () {
const [picFile, setPicFile] = useState();
const handleGetClick = async () => {
API.findAll()
.then(res => {
console.log(res)
})
.catch(err => console.error(err))
}
const handleUploadClick = async (e) => {
e.preventDefault();
// console.log(picFile);
// create new formData instance
const bodyFormData = new FormData();
// append single file to formData instance
bodyFormData.append('picFile', picFile.selectedFile);
// log items in formData object
for (const element of bodyFormData) {
console.log(element);
}
// send formData obj to axios function
API.save(bodyFormData)
.then(res => {
//console.log(res)
})
.catch(err => console.error(err))
}
const onFileChange = (e) => {
console.log(`e.target.files[0]`, e.target.files[0])
setPicFile({ selectedFile: e.target.files[0] });
}
return (
<div>
<h1>My Puzzle Gallery</h1>
<form encType='multipart/form-data'>
<input type='file' name='picFile' onChange={onFileChange} />
<br />
<br />
<button onClick={handleUploadClick}>Upload a picture</button>
</form>
<br />
<br />
<button onClick={handleGetClick}>Get pictures</button>
<br />
<br />
<img src='https://placekitten.com/640/360' alt='kitten' />
</div>
);
}
client\src\services\API.js
import axios from 'axios';
const API = {
login: (username, password) => {
const obj = {
username: username,
password: password
};
return axios.post('/api/auth/login', obj);
},
register: (username, password) => {
const obj = {
username: username,
password: password
};
return axios.post('/api/auth/register', obj);
},
logout: function () {
return axios.get('api/auth/logout');
},
save: function (form) {
return axios.post('api/puzzle/', form).catch(err=>console.error(err));
},
findAll: function () {
return axios.get('api/puzzle/');
},
}
export default API;
server\routes\api\puzzle\index.js
const router = require('express').Router();
const puzzleController = require('../../../controllers/puzzleController');
// Matches with '/api/puzzle'
router.route('/')
.get(puzzleController.findAll)
.post(puzzleController.save);
// Matches with '/api/books/:id'
router.route('/delete/:id')
.delete(puzzleController.remove);
module.exports = router;
server\server.js
const path = require('path');
const express = require('express');
const passport = require('./config/passport');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const helmet = require('helmet');
const morgan = require('morgan');
const corsOptions = require('./config/cors.js');
const routes = require('./routes');
const { v1: uuidv1 } = require('uuid');
// console.log(uuidv1());
const PORT = process.env.PORT || 3001;
const app = express();
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/puzzlegallery', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
mongoose.set("useCreateIndex", true);
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(helmet({ contentSecurityPolicy: false }));
app.use(session({ secret: 'sassy', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors(corsOptions));
app.use(morgan('dev'));
app.use(routes);
// for Reactjs ##################
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
// #################################################
if (process.env.NODE_ENV === 'production') {
app.get('*', (_, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
}
app.listen(PORT, (err) => {
if (err) throw err;
console.log(
`🌎 Server is Ready and Listening on http://localhost:${PORT}`
); // eslint-disable-line no-console
});
EDIT:
This seemed to work. Thanks again!!
const path = require('path');
const router = require('express').Router();
const puzzleController = require('../../../controllers/puzzleController');
const multer = require('multer');
const { v1: uuidv1 } = require('uuid');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../../../../tmp/my-uploads'))
},
filename: function (req, file, cb) {
cb(null, uuidv1())
}
})
const upload = multer({ storage: storage });
// Matches with '/api/puzzle'
router.route('/')
.get(puzzleController.findAll)
// Matches with '/api/books/:id'
router.route('/delete/:id')
.delete(puzzleController.remove);
router.use(upload.single('picFile'));
router.route('/')
.post(puzzleController.save);
module.exports = router;
you cannot call the middleware inside the save function like this.
I cloned your repo and added the following code in server.js and it's working fine and I got the value in the req.file.
const multer = require('multer');
const upload = multer({ dest: 'uploads/'});
app.post('/api/puzzle/', upload.single('pictureFile'),(req,res,next)=>{
console.log("req.file22222222", req.file);
})

The requested URL /about-us was not found on this server

After executing the export, on the host, when I enter the link manually or refresh the page, a message is not displayed.
I have the server.js and the next module. Do I need to do anything else?
server.js
const express = require('express');
const next = require('next');
const { parse } = require('url');
const DEV = process.env.ENVIRONMENT !== 'production';
const PORT = 4567;
const app = next({dir: '.', dev: DEV});
const handle = app.getRequestHandler();
const getRoutes = require('./routes');
const routes = getRoutes();
app.prepare().then(() => {
const server = express();
server.get('*', (req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
const route = routes[pathname];
if (route) {
return app.render(req, res, route.page, route.query);
}
return handle(req, res);
});
server.listen(PORT, (err) => {
if (err) throw err;
console.log(`> READY FOR LIFOTFF http://localhost:${PORT}`);
});
});
Router.js
module.exports = () => {
return {
'/': { page: '/' },
'/404': { page: '/404' },
'/about-us': { page: '/about-us' },
}
}
next.config.js
const getRoutes = require('./routes');
module.exports = {
useFileSystemPublicRoutes: true,
exportPathMap: getRoutes
}
I add trailingSlash: true to next.config.js,it's working.
my new next.config:
const getRoutes = require('./routes');
module.exports = {
trailingSlash: true,
useFileSystemPublicRoutes: true,
exportPathMap: getRoutes,
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}

whenever I try to make a post request in postman i get error "Todo validation failed: task: Path `task` is required"

this is my app.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const inputRoutes = require("./routes/input");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(cors());
app.use((req, res, next) => {
res.setHeader("Acess-Control-Allow-Origin", "*");
res.setHeader(
"Acess-Control-Allow-Methods",
"OPTIONS ,GET ,POST ,PUT,PATCH , DELETE"
);
res.setHeader("Acess-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.use("/input", inputRoutes);
mongoose
.connect("mongodb://localhost:27017/MEAN", { useNewUrlParser: true })
.then(result => {
app.listen(2400);
})
.catch(err => console.log(err));
this is my routes/input.js
const express = require("express");
const router = express.Router();
const inputController = require("../controller/input");
router.post("/todo", inputController.createTodos);
module.exports = router;
this is my controller,input.js
const Todo = require("../models/todos");
const { validationResult } = require("express-validator/check");
exports.createTodos = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const error = new Error("validation failed due to incorrect data");
error.statusCode = 442;
throw error;
}
const task = req.body.task;
const status = req.body.status;
console.log(task);
console.log(status);
const todo = new Todo({
task: task,
status: status
});
todo
.save()
.then(result => {
console.log(task);
res.status(201).json({
message: "post created sucessfully",
post: result
});
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};
this is my model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const todoSchema = new Schema(
{
task: {
type: String,
required: true
},
status: {
type: Boolean,
default: false
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Todo", todoSchema);
You need to send JSON request in the postman first choosing raw option, and then json in the right dropdown.
Also you seem to use express-validator package, but you don't use it in router.
In the router you can use it like this:
const express = require("express");
const router = express.Router();
const { check } = require("express-validator");
const inputController = require("../controller/input");
router.post("/todo", [
check("task")
.not()
.isEmpty()
], inputController.createTodos);
module.exports = router;
Also in controller you should import the validationResult from express-validator,
and validate the result like this:
const { validationResult } = require('express-validator');
exports.createTodos = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
....
}

Categories

Resources