So I am having trouble with this error. I am tapping into the OPENAI API to generate AI images and then creating an entry in my DB. I am able to generate and display the images, but whenever I click my button to create an entry in my database, I get this error. I am uploading an image to Cloudinary to get back a URL so I can POST to my backend(MongoDB), but I keep getting this 500 Internal Error, and not sure what is wrong. Is the URL too long? What is the fix?
const handleSubmit = async (e) => {
e.preventDefault();
console.log(form.prompt)
console.log(form.photo)
if(form.prompt && form.photo) {
setLoading(true);
try {
const response = await fetch('http://localhost:8080/api/v1/post'
, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(form)
})
await response.json();
console.log("RESPONSE: ", response)
navigate('/')
} catch (err) {
alert(err)
} finally {
setLoading(false)
}
} else {
alert("Please enter a prompt and generate an image.")
}
}
//CREATE POST
router.route('/').post(async(req, res) => {
try {
const { name, prompt, photo } = req.body;
const photoUrl = await cloudinary.uploader.upload(photo);
console.log("photoURL: ", photoUrl)
const newPost = await Post.create({
name,
prompt,
photo: photoUrl.url,
})
res.status(201).json({ success: true, data: newPost})
} catch (error) {
res.status(500).json({ success: false, message: error})
}
})
Index.js in Server folder
import postRoutes from './routes/postRoutes.js'
import dalleRoutes from './routes/dalleRoutes.js'
dotenv.config();
const app = express();
app.use(cors())
app.use(express.json( {limit: '50mb'}))
app.use('/api/v1/post', postRoutes)
app.use('/api/v1/dalle', dalleRoutes)
app.get('/', async (req, res) => {
res.send('Hello from DALL-E!')
})
const startServer = async () => {
try {
connectDB(process.env.MONGODB_URL);
app.listen(8080, () => console.log('Server has started on port http://localhost:8080'))
} catch (error) {
console.log(error)
}
}
startServer();
function CreatePost() {
const navigate = useNavigate();
const [form, setForm ] = useState({
name: '',
prompt: '',
photo: ''
});
.....
Related
I'm trying to sign up new user, when I'm sending the post request the server register the user well, and I can see them in my data base, but I can't see the success log in my console (I can catch the error and it logs in my console).
Server side code:
var express = require("express");
const { Error } = require("mongoose");
const passport = require("passport");
var router = express.Router();
const User = require("../models/user");
const catchAsync = require("../utils/catchAsync");
router.post(
"/register",
catchAsync(async (req, res) => {
try {
const { email, username, password } = req.body;
const user = new User({ email, username });
await User.register(user, password);
} catch (e) {
throw new Error("Error signing up");
}
})
);
module.exports = router;
Client side code:
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
await fetch("http://localhost:9000/users/register", {
method: "POST",
body: JSON.stringify({
username,
email,
password,
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
if (res && !res.ok) {
throw new Error("ERROR");
}
console.log("Success");
})
.catch((e) => {
console.log(e.message);
});
} catch (e) {
console.log(e.message);
}
};
You are mixing the async/await style and the older .then() Promise-style. Choose one or the other (I strongly recommend async/await)
You are not transforming fetch's response into JSON, leaving it in Promise state.
Your server is never responding to the client! You need to add res.end(), res.send(), res.json() or something.
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
const response = await fetch("http://localhost:9000/users/register", {...});
const serverResponse = await response.text(); // or response.json() if your servers sends JSON back
console.log("Success! serverResponse is = ", serverResponse ); // "Done!"
} catch (e) {
console.log(e.message);
}
};
Server :
...
await User.register(user, password);
res.send("Done!"); // or res.json({ status : "ok" }); etc.
I have a PUT in a REST API that should display an error message that says "upvoted already" if the vote_score is 1 (that is, they voted already), but instead I get a generic "internal server error" message in alert which is not good UX. That's always what the error will say with what I have tried so far.
How can I get my error message to display as "upvoted already"? Or for that matter, how can I get any error message to show up with a message? I hope I have provided enough information with the API code followed with the front-end code.
What I have tried thus far is trying different things like res.status(200).json({ error: err.toString() }); and next(err).
Hopefully something simple, I am hoping for a ELI5 type answer because I am a beginner and my error-handling game is weak. Thanks.
const db = require('../db');
const express = require('express');
const debug = require('debug')('app:api:vote');
const Joi = require('joi');
const auth = require('../middleware/auth');
const admin = require('../middleware/admin');
const { required } = require('joi');
const router = express.Router();
router.use(express.urlencoded({ extended: false }));
router.use(express.json());
// general error handler
const sendError = (err, res) => {
debug(err);
if (err.isJoi) {
res.json({ error: err.details.map((x) => x.message + '.').join('\n') });
} else {
res.json({ error: err.message });
}
};
router.put('/upvote/:emojiId/', auth, async (req, res, next) => {
try {
const schema = Joi.object({
emoji_id: Joi.number().required(),
user_id: Joi.number().required(),
vote_score: Joi.number(),
});
const vote = await schema.validateAsync({
emoji_id: req.params.emojiId,
user_id: req.user.user_id,
vote_score: 1,
});
if (!(await db.findVoteByUser(vote.emoji_id, vote.user_id))) {
const upvote = await db.upvote(vote);
} else if ((await db.findVoteByUser(vote.emoji_id, vote.user_id)) == 1) {
throw new Error('Upvoted already');
}
const upvoteScore = await db.getJustUpvotesForEmoji(vote.emoji_id);
res.json(upvoteScore);
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
module.exports = router;
And the front-end...
$(document).on('click', '.upvote-emoji-button', (evt) => {
const button = $(evt.currentTarget);
const emoji_id = button.data('id');
$.ajax({
method: 'PUT',
url: `/api/vote/upvote/${emoji_id}`,
data: emoji_id,
dataType: 'json',
})
.done((res) => {
if (res.error) {
bootbox.alert(res.error);
} else {
// $('#search-emoji-form').trigger('submit');
button.addClass('btn-danger').removeClass('btn-primary');
button.parent().next().next().html(res.upvotes);
button.parent().next().next().next().next().html(res.vote_count);
button.parent().next().next().next().next().next().html(res.total_score);
}
})
.fail((xhr, textStatus, err) => {
bootbox.alert(err);
});
});
try to replace
res.status(500).json({ error: err.toString() });
with
res.status(400).send(err.toString());
Documentation
Here is what I ended up doing. It took care of my error and a few other things too. :)
//setup
const db = require('../db');
const express = require('express');
const debug = require('debug')('app:api:vote');
const Joi = require('joi');
const auth = require('../middleware/auth');
const admin = require('../middleware/admin');
const { required } = require('joi');
const router = express.Router();
router.use(express.urlencoded({ extended: false }));
router.use(express.json());
// general error handler
const sendError = (err, res) => {
debug(err);
if (err.isJoi) {
res.json({ error: err.details.map((x) => x.message + '.').join('\n') });
} else {
res.json({ error: err.message });
}
};
router.put('/upvote/:emojiId/', auth, async (req, res, next) => {
let vote = {};
try {
const schema = Joi.object({
emoji_id: Joi.number().required(),
user_id: Joi.number().required(),
vote_score: Joi.number(),
});
vote = await schema.validateAsync({
emoji_id: req.params.emojiId,
user_id: req.user.user_id,
vote_score: 1,
});
if (!(await db.findUserByID(req.user.user_id))) {
throw new Error('log in again.');
}
const tester = await db.findVoteByUser(vote.user_id, vote.emoji_id);
if (!(await db.findVoteByUser(vote.user_id, vote.emoji_id))) {
await db.upvotePost(vote);
const upvoteScore = await db.getJustUpvotesForEmoji(vote.emoji_id);
const message = 'message';
upvoteScore[message] = 'Upvote sent.';
const action = 'action';
upvoteScore[action] = 1;
res.json(upvoteScore);
} else if (tester.vote_score == -1) {
await db.upvotePut(vote);
const upvoteScore = await db.getJustUpvotesForEmoji(vote.emoji_id);
const message = 'message';
upvoteScore[message] = 'Downvote changed to upvote.';
const action = 'action';
upvoteScore[action] = 2;
res.json(upvoteScore);
} else {
await db.deleteVoteByUserIdAndEmojiId(vote);
const upvoteScore = await db.getJustUpvotesForEmoji(vote.emoji_id);
const message = 'message';
upvoteScore[message] = 'Upvote deleted.';
const action = 'action';
upvoteScore[action] = 3;
res.json(upvoteScore);
}
} catch (err) {
sendError(err, res);
}
});
module.exports = router;
and front end..
$(document).on('click', '.upvote-emoji-button', (evt) => {
const button = $(evt.currentTarget);
const emoji_id = button.data('id');
$.ajax({
method: 'PUT',
url: `/api/vote/upvote/${emoji_id}`,
data: emoji_id,
dataType: 'json',
})
.done((res) => {
if (res.error) {
bootbox.alert(res.error);
} else {
if (res.action == 1) {
button.addClass('btn-danger').removeClass('btn-primary');
button.parent().next().next().html(res.upvotes);
button.parent().next().next().next().next().html(res.vote_count);
button.parent().next().next().next().next().next().html(res.total_score);
bootbox.alert(res.message);
} else if (res.action == 2) {
button.addClass('btn-danger').removeClass('btn-primary');
button.parent().next().children().addClass('btn-primary').removeClass('btn-danger');
button.parent().next().next().html(res.upvotes);
button.parent().next().next().next().next().html(res.vote_count);
button.parent().next().next().next().next().next().html(res.total_score);
bootbox.alert(res.message);
} else if (res.action == 3) {
button.removeClass('btn-danger').addClass('btn-primary');
button.parent().next().next().html(res.upvotes);
button.parent().next().next().next().next().html(res.vote_count);
button.parent().next().next().next().next().next().html(res.total_score);
bootbox.alert(res.message);
}
}
})
.fail((xhr, textStatus, err) => {
bootbox.alert(err);
// alert(`${textStatus}\n${err}\n${xhr.status}`);
});
});
So whenever the app is loaded it should check for user Auth using the loadUser(), the problem I'm having is that if there is no token in localStorage, the server won't return any errors(when its suppose to). I looked at the code for auth(backend), and it returns a status meassage when no token received, I was wondering is it because no token isn't a type of error, that's way the server didn't send an error response?
Below are the code snippets:
auth.js(backend)
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = function (req, res, next) {
//get token from header
const token = req.header("x-auth-token");
// check if not token
if (!token) {
return res.status(401).json({ msg: "no token, auth denied" });
}
//verify token
try {
const decoded = jwt.verify(token, config.get("jwtSecret"));
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({
msg: "token isnt valid",
});
}
};
App.js
const App = () => {
useEffect(() => {
if (localStorage.token) {
setAuthToken(localStorage.token);
store.dispatch(loadUser());
}
}, []);
auth.js Redux
export const loadUser = () => async (dispatch) => {
console.log("from auth.js");
if (localStorage.token) {
setAuthToken(localStorage.token);
}
try {
const res = await axios.get("/api/auth");
console.log("inside auth.js get auth route");
dispatch({
type: USER_LOADED,
payload: res.data,
});
} catch (err) {
console.log("error from auth.js");
dispatch({
type: AUTH_ERROR,
});
}
};
Basically the code inside catch(err) { //code }
is not executed.
Silly of me, added else condition into App.js solved the issue.
I did follow a tutorial of how to integrate mailchimp with node backend. I have never touched back end, so am pretty lame at it.
When I POST to their API I get the subscriber's credentials, but I get an error back - "Assignment to constant variable". Reading through the web and other SO questions, it seems like I am trying to reassign a CONST value.
I had a goooooooooood look at my code and the only thing I have noticed that might be issues here is
request(options, (error, response, body) => {
try {
const resObj = {};
if (response.statusCode == 200) {
resObj = {
success: `Subscibed using ${email}`,
message: JSON.parse(response.body),
};
} else {
resObj = {
error: ` Error trying to subscribe ${email}. Please, try again`,
message: JSON.parse(response.body),
};
}
res.send(respObj);
} catch (err) {
const respErrorObj = {
error: " There was an error with your request",
message: err.message,
};
res.send(respErrorObj);
}
});
I have noticed I am creating an empty object called "resObj", then trying to assign a value to it.
I have tried changing the CONST to LET, but I get an error saying: "resObj is not defined".
Here is my front end code:
import React, { useState } from "react";
import "./App.css";
import Subscribe from "./components/Subscribe";
import Loading from "./components/Loading/Loading";
import axios from "axios";
import apiUrl from "./helpers/apiUrl";
function App() {
const [loading, setLoading] = useState(false);
const [email, setEmail] = useState("");
const handleSendEmail = (e) => {
setLoading(true);
console.log(email);
axios
.post(`${apiUrl}/subscribe`, { email: email })
.then((res) => {
if (res.data.success) {
alert(`You have successfully subscribed!, ${res.data.success}`);
setEmail("");
setLoading(false);
} else {
alert(`Unable to subscribe, ${res.data.error}`);
console.log(res);
setLoading(false);
setEmail("");
}
})
.catch((err) => {
setLoading(false);
alert("Oops, something went wrong...");
console.log(err);
setEmail("");
});
e.preventDefault();
};
const handleInput = (event) => {
setEmail(event.target.value);
};
// const handleLoadingState = (isLoading) => {
// setLoading({ isLoading: loading });
// console.log(loading);
// };
return (
<div className='App'>
<h1>Subscribe for offers and discounts</h1>
{loading ? (
<Loading message='Working on it...' />
) : (
<Subscribe
buttonText='Subscribe'
value={email}
handleOnChange={handleInput}
handleOnSubmit={handleSendEmail}
/>
)}
</div>
);
}
export default App;
And the Back end code:
const restify = require("restify");
const server = restify.createServer();
const corsMiddleware = require("restify-cors-middleware");
const request = require("request");
require("dotenv").config({ path: __dirname + "/variables.env" });
const subscribe = (req, res, next) => {
const email = req.body.email;
const dataCenter = process.env.DATA_CENTER;
const apiKey = process.env.MAILCHIMP_API_KEY;
const listID = process.env.LIST_ID;
const options = {
url: `https://${dataCenter}.api.mailchimp.com/3.0/lists/${listID}/members`,
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `apikey ${apiKey}`,
},
body: JSON.stringify({ email_address: email, status: "subscribed" }),
};
request(options, (error, response, body) => {
try {
const resObj = {};
if (response.statusCode == 200) {
resObj = {
success: `Subscibed using ${email}`,
message: JSON.parse(response.body),
};
} else {
resObj = {
error: ` Error trying to subscribe ${email}. Please, try again`,
message: JSON.parse(response.body),
};
}
res.send(respObj);
} catch (err) {
const respErrorObj = {
error: " There was an error with your request",
message: err.message,
};
res.send(respErrorObj);
}
});
next();
};
const cors = corsMiddleware({
origins: ["http://localhost:3001"],
});
server.pre(cors.preflight);
server.use(restify.plugins.bodyParser());
server.use(cors.actual);
server.post("/subscribe", subscribe);
server.listen(8080, () => {
console.log("%s listening at %s", server.name, server.url);
});
If anyone could help I would be very grateful. The subscription form works, but I need to clear that bug in order for my front end to work correctly onto submission of the form.
Maybe what you are looking for is Object.assign(resObj, { whatyouwant: value} )
This way you do not reassign resObj reference (which cannot be reassigned since resObj is const), but just change its properties.
Reference at MDN website
Edit: moreover, instead of res.send(respObj) you should write res.send(resObj), it's just a typo
I'm trying to send some data from a React form to my Express back end. To do this I'm using fetch where I'm trying to send some variable data from react. I'm console logging the data before running the fetch to see if it is there, console log can see the data.
My error states
[0] (node:2966) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'message' of undefined
So it seems like my Express back end can't see the variable data.
How I'm sending the data from react
handleSubmit = async e => {
e.preventDefault();
console.log("Submit was pressed!");
if (this.state.email === "") {
}
const { name } = this.state;
const query = this.state.query;
const subject = "kontakt fra nettside";
const message = { name, query };
console.log(message.name, message.text, "data is");
fetch(
"http://localhost:5000/api/email", variabler
{
method: "POST",
cache: "no-cache",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
content_type: "application/json"
},
body: JSON.stringify(message, subject)
}
); //.then(response => response.json());
};
My file for retrieving the data from the front end in Express
const emailConfig = require("./emailConfig")();
const mailgun = require("mailgun-js")(emailConfig);
exports.sendEmail = (recipient, message, attachment) =>
new Promise((resolve, reject) => {
const data = {
from: "Test <test#test.no>", // Real email removed from this post
to: recipient,
subject: message.subject,
text: message.query,
inline: attachment,
html: message.html
};
mailgun.messages().send(data, error => {
if (error) {
return reject(error);
}
return resolve();
});
});
and sendMail.js
const express = require("express");
const sendMail = express.Router();
const emailUtil = require("./emailUtil");
const { sendEmail } = emailUtil;
sendMail.post("/", async (req, res, next) => {
// const { recipient, message } = req.body;
console.log("Request mottatt");
const recipient = "test#test.no";
const message = req.body.message;
try {
await sendEmail(recipient, message);
res.json({ message: "Your query has been sent" });
console.log("Message has been sent");
await next();
} catch (e) {
await next(e);
console.log("nah", e);
}
});
module.exports = sendMail;
I can't figure out where the error is, any ideas? :)