I need to upload images from the front and that they reach the back to be able to show themselves but I have not been able to find the trick, if someone knows I would greatly appreciate it.
this is my error in the server
req files : undefined
ss ss
I'm using a react library for forms 'React-hook-form', it would be supposed that only with the field and the selected image it would be sent but when looking at the console I get undefined in the image field and in the others if it captures me the value
my front
const postCategories = async (data) => {
try {
setLoading(true);
const response = await instance.post("/categories", data);
console.log(response);
setLoading(false);
toast.success(response.data.msg);
getCategories();
setModalAdd(false);
} catch (err) {
console.log(err);
setLoading(false);
toast.error(err.response.data.msg);
}
};
console.log(data);
const bodyModalAdd = (
<Box sx={style}>
<h3 className="text-xl font-semibold">Añadir categoria</h3>
<form onSubmit={handleSubmit(postCategories)}>
<div>
<label>imagen</label>
<input
type="file"
{...register("urlImage", { required: true, })}
/>
</div>
my back
export const registarCategoria = async (req, res) => {
console.log("Intentas pasar aunque sea");
const { nombre, descripcion } = req.body;
console.log("req files : " , req.files);
console.log(nombre, descripcion);
if (nombre !== undefined && descripcion !== undefined) {
const categoriaExiste = await Categoria.findOne({
where: {
nombre: nombre,
},
});
if (categoriaExiste) {
return res.status(400).json({
msg: "Ya esta registrada la categoria ya esta registrado",
success: false,
});
}
try {
let resultadoImg = undefined;
if(req.files?.image){
resultadoImg = await uploadImage(req.files.image.tempFilePath)
}
if(resultadoImg){
await Categoria.create({
nombre,
descripcion,
urlImage : resultadoImg?.secure_url,
});
return res
.status(201)
.json({ msg: "Categoria creada correctamente", success: true });
}else{
return res.status(400).json({ msg: "No se pudo crear la categoria, falta imagen", success: false });
}
} catch (err) {
console.error(err);
}
} else {
res.status(400).json({
success: false,
msg: "Faltan datos",
});
}
};
Related
when I click submit button, then web and terminal will return error like me title
but i try postman is ok , so i think is my axios setting error,how can i fixed this error? I found many similar questions, but can't not help me
the other question is , my form tag action is "/addItems", but i sending request , i got this error CANNOT POST / addItems Post http://localhost:3000/addItems 404 (Not Found)
(axios setting )
post(id, title, description, price, avatar) {
let token;
if (localStorage.getItem("user")) {
token = JSON.parse(localStorage.getItem("user")).token;
} else {
token = "";
}
const formData = new FormData();
// formData.append("id", id);
// formData.append("title", title);
// formData.append("description", description);
// formData.append("price", price);
formData.append("avatar", avatar);
return axios.post(
API_URL + "/addItems",
{ formData },
{
headers: {
Authorization: token,
"Content-Type": "multipart/form-data"
}
}
);
}
(item.route)
itemRouter.post("/addItems", upload.single("avatar"), async (req, res) => {
let { id, title, description, price, avatar } = req.body;
if (req.user.isMember()) {
return res.status(400).send("Only admin can add new items");
}
console.log(req.file);
avatar = req.file.path;
const newItem = new Item({
id,
title,
description,
price,
avatar
});
try {
await newItem.save();
console.log(req.file);
res.status(200).send("New item has been saved.");
} catch (err) {
res.status(400).send("Error");
console.log(err);
}
});
(addItemsComponent)
const handleChangePost = () => {
if (currentUser.user.role !== "admin") {
window.alert("Member can't not post item!! ");
navigate("/");
} else {
ItemService.post(avatar)
.then(() => {
window.alert("Post successfully");
navigate("/");
})
.catch((error) => {
console.log(error);
console.log(error.response);
setErrorMessage(error.response.data);
});
}
};
return (
<div>
<form action="/addItems" method="post" enctype="multipart/form-data">
<input onChange={handleChangeAvatar} value={avatar} type="file" name="avatar" />
<button type="submit" onClick={handleChangePost}>
Submit
</button>
</form>
</div>
);
Try this
return axios.post(API_URL + "/addItems", formData,
{
headers: {
Authorization: token,
"Content-Type": "multipart/form-data"
}
}
);
I am Selecting Multiple Files and using Multer saving Files to a specific folder. But if i am uploading Single file it is working Fine but if Selected More than two it is giving me an
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I am frustrated solving it. Can anyone one help me out yrr.
<div className="mb-3" >
<CFormLabel htmlFor="formFileMultiple">Select Resources</CFormLabel>
<CFormInput
multiple
onChange={(event) => formikProps.setFieldValue('fileName', event.target.files)}
accept="application/pdf, application/zip"
type="file" id="formFileMultiple" />
<p style={{ color: 'red' }}>{formikProps.touched.fileName && formikProps.errors.fileName}</p>
</div>
const handleAddResources = async ({ fileName }) => {
try {
const data = new FormData();
// data.append("fileName", fileName);
data.append("courseId", props.currentUser.item.course_id);
for (let i = 0; i < fileName.length; i++) {
// newArr.push(fileName[i]);
data.append("fileName", fileName[i]);
let response = await axios.post(`${ConfigData.SERVER_URL}/admin/resources/addResources`, data, {
})
if (response.data.status == false) {
throw Error(response.data.message)
}
else {
console.log("Success")
setthrowAlert(true);
}
}
} catch (error) { console.log(error) }
}
router.post('/addResources', fileUpload.array('fileName', 100), async (req, res) => {
try {
if (req.body && req.files) {
req.files.map(async(item) => {
console.log("ITEM--->", item);
let ResourcePost = new ResourcesPost({
originalname: item.originalname,
FileName:item.filename,
courseId: req.body.courseId,
mimetype:item.mimetype,
encoding:item.encoding,
size:item.size,
destination:item.destination
})
let uploadData = await ResourcePost.save()
if (uploadData) {
res.status(200).json({ status: true, data: uploadData })
} else {
res.status(500).json({ status: false, message: err.message })
}
})
} else {
console.log("Resourses Not Found !");
}
}
catch (error) {
console.log(error);
}
})
I need to pass author's email in my posts. I though I can do it by joining tables in my posts route, but it doesn't really work.
Here is my route :
router.get("/posts", async (req, res) => {
const { id } = req.session.user;
//const usersPosts = await user.$relatedQuery("posts");
try {
const user = await User.query().findById(id);
if (!user) {
return res.status(401).send("User was not found");
}
const posts = await Post.query()
.select([
"users.email",
"images.name",
"posts.category",
"posts.title",
"posts.description",
"posts.created_at"
])
.join("images", { "posts.image_id": "images.id" });
.join("users", { "posts.user_email": "users.email" });
console.log("it worked");
return res.status(200).send({ posts: posts });
} catch (error) {
console.log(error);
return res.status(404).send({ response: "No posts found" });
}
});
Here is code with my axios fetching the route :
function Home(props) {
const [posts, setPosts] = useState([]);
const getPosts = async () => {
try {
let response = await axios.get("http://localhost:9090/posts", {
withCredentials: true
});
console.log(response.data.posts);
setPosts(response.data.posts);
} catch (error) {
console.log(error.data);
}
};
useEffect(() => {
getPosts();
}, []);
And this is how I tried to return it:
{posts.map((post, index) => {
return (
<>
Author:<br></br>
<small>{post.user_email}</small>
</p>
<p>
Category:<br></br>
<small>{post.category}</small>
</p>
<p>
Description:<br></br>
<small>{post.description}</small>
</p>
<p>
Created: <br></br>
<small>{post.created_at}</small>
Everything works except the fetching Author.
a typo its user_email not users_email
your sending email in the value assingned to user_email and in front end using users_email
I have tried to post data in postman and it returns a json object , the methods are working good .
I have a problem to get the value of attribut when the api respond with a json object .
the forma of json like this :
{
"success" : "true"
}
the api method :
router.post("/sickers/user/login/", (req, res) => {
var values = JSON.parse(req.body);
var pass = values.password;
var email = values.email;
//console.log(values);
if (pass !== null || pass !== "") {
try {
con.connect();
con.query("SELECT Password FROM `sickers` WHERE Email='" + email + "'", function(err, rows, field) {
if (err) {
console.log(err);
res.send("an error detected try later");
} else {
try {
if (pass == rows[0].Password) {
//trying to send correct message from here
res.send({ success: "true" });
console.log("yes")
} else {
console.log("no")
res.send({ success: "false" });
}
} catch {
console.log("no")
res.send({ success: "false" });
}
}
});
} catch (e) {
res.send("no data found");
console.log("obj not found");
}
}
con.end();
});
the post method from a react app is :
//submit values
async submithandler(e) {
e.preventDefault();
try{
await fetch('http://localhost:8000/api/sickers/user/login/',{
method:'post',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
password:this.state.password,
email:this.state.email
})
})
.then(response=>{
this.setState({data:response})
alert(data.success);
})
}catch(e){
alert(e)
}
}
the data declaration in state : data:[]
the error is that the data is undefined .
when you do an api call using fetch request, it returns a promise that contains the response and that response is resolved by the first .then(). after resolving this first promise it returns another response and you need to resolve it with another .then()
Please check the working example below:
import React, {Component} from "react";
class FetchExample extends React.Component {
state = {
isLoading: false,
questions: [],
error: null
};
fetchQuestions = () => {
fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,)
.then(response => {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(data => {
console.log(data);
this.setState({
questions: data,
isLoading: false
})
});
}
)
.catch(function (error) {
console.log('Error: ', error);
this.setState({error, isLoading: false})
});
};
render() {
const {isLoading, questions, error} = this.state;
return (
<React.Fragment>
<h1>Random Question</h1>
<button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
{error ? <p>{error.message}</p> : null}
{!isLoading && questions.results ? (
questions.results.map((questions, index) => { //something right here
//is erroring
const {question, category, type, difficulty} = questions;
return (
<div key={index}>
<p>Question: {question}</p>
<p>Question Type: {type}</p>
<p>Difficulty: {difficulty}</p>
<hr/>
</div>
);
})
) : isLoading ? (
<h3>Loading...</h3>
) : null}
</React.Fragment>
);
}
}
export default FetchExample;
there is two problems here at this example with both parts api and react app ,
the first thing I did is to understand cors and how it works in express and I found that I should do the following steps to the api :
run
npm install cors
second is to add
const cors =require('cors')
and then :
app.use(cors());
and last step is inside the router post I should add cors :
router.post('path',cors(),(req,res)....
about react app code it just need to remove module="no-cors"
and then it works .
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
You need to be authenticated to vote on a poll. When you vote on a poll, there are 2 issues:
You can vote an infinite number of times until you leave or reload the page
When you reload the page, you are finally prevented from voting but instead of having the option you voted on pre-selected, it's always the second option that is preselected.
WHAT SHOULD HAPPEN:
Sign up/ Login, then vote on a poll. The moment you click on an option, the poll voting choice you made is locked and you can't vote more on that poll.
HOW THE FLOW OF MY CURRENT CODE WORKS:
When a user clicks on an option, the counter is increased and the vote is then saved in an array that is pushed to the User object in the database.
When the component loads, the database data for votes for the currently logged in user is saved through the ngOninit() method inside the local votes variable which is then used to check on which poll the user already voted and what vote he made. The issue is that the choice is made is always choice2 when that is not actually the case.
I understand why you can vote many times until the page reloads, but I just don't know how to immediately lock the poll after the user voted, on the client and on the backend (prevent more votes from being registered if user already voted on poll).
As for why it is already the second choice that is pre-selected, I have no idea.
CODE:
HTML
<div class="formWidth">
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div class="form-group">
<label class="inputTitle" for="title">Poll Title</label>
<input
type="text"
id="title"
class="form-control"
[ngModel]="poll?.title"
name="title"
required maxlenth="30">
<label class="inputTitle" for="choice1">Choice1</label>
<input
type="text"
id="choice1"
class="form-control"
[ngModel]="poll?.choice1"
name="choice1"
required maxlenth="20">
<label class="inputTitle" for="choice2">Choice2</label>
<input
type="text"
id="choice2"
class="form-control"
[ngModel]="poll?.choice2"
name="choice2"
required maxlenth="20">
</div>
<button type="button" class="btn btn-danger" (click)="onClear(f)">Clear</button>
<button class="btn btn-primary" type="submit">Save</button>
</form>
</div>
COMPONENT
export class PollComponent {
#Input() poll: Poll;
constructor(private pollService: PollService) {}
votes: any;
// Pie
public pieChartLabels:string[] = [];
public pieChartData:number[] = [];
public pieChartType:string = 'pie';
public pieChartOptions:any = {};
ngOnInit() {
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
this.pieChartLabels = [this.poll.choice1, this.poll.choice2];
this.pieChartType = 'pie';
this.pieChartOptions = {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItem, data) {
var allData = data.datasets[tooltipItem.datasetIndex].data;
var tooltipLabel = data.labels[tooltipItem.index];
var tooltipData = allData[tooltipItem.index];
return tooltipLabel + ": " + tooltipData + "%";
}
}
}
}
this.pollService.voted(localStorage.getItem('userId')).subscribe(
data => {
var result = JSON.parse(data);
this.votes = result.votes;
},
err => { console.log("NGONINIT ERROR: "+ err) },
() => { }
);
}
onEdit() {
this.pollService.editPoll(this.poll);
}
onDelete() {
this.pollService.deletePoll(this.poll)
.subscribe(
result => console.log(result)
);
}
onChoice1() {
this.pollService.increaseCounter1(this.poll);
this.onVote1();
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
}
onChoice2() {
this.pollService.increaseCounter2(this.poll);
this.onVote2();
var result1 = parseFloat(((this.poll.counter1/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
var result2 = parseFloat(((this.poll.counter2/(this.poll.counter2+this.poll.counter1))*100).toFixed(2));
this.pieChartData = [result1, result2];
}
onVote1() {
this.pollService.voteOn(this.poll.pollID, localStorage.getItem('userId'), 1);
}
onVote2() {
this.pollService.voteOn(this.poll.pollID, localStorage.getItem('userId'), 2);
}
belongsToUser() {
return localStorage.getItem('userId') == this.poll.userId;
}
alreadyVotedFor(choice: number) {
var result = "";
if (this.votes) {
for (var i = 0; i < this.votes.length; i ++) {
if (this.votes[i].pollID == this.poll.pollID) {
result = "disabled";
if (this.votes[i].choice == choice) {
result = "selected";
}
}
}
}
return result;
}
// events
public chartClicked(e:any):void {
}
public chartHovered(e:any):void {
}
}
SERVICE
updatePoll(poll: Poll) {
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/poll/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
});
}
increaseCounter1(poll: Poll) {
poll.counter1++;
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
this.http.patch('https://voting-app-10.herokuapp.com/poll/vote/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
increaseCounter2(poll: Poll) {
poll.counter2++;
const body = JSON.stringify(poll);
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/poll/vote/' + poll.pollID, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
voteOn(pollID: string, userID: string, choice: number) {
var user;
this.http.get('https://voting-app-10.herokuapp.com/user/'+userID)
.map(response => response.json())
.subscribe(
json => {
user = JSON.parse(json);
if (user.votes == undefined) {
user.votes = [{pollID, choice}];
} else {
user.votes.push({pollID, choice});
}
const body = user;
const token = localStorage.getItem('token')
? localStorage.getItem('token')
: '';
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token
});
return this.http.patch('https://voting-app-10.herokuapp.com/user/', body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
})
.subscribe();
}
)
}
voted(userID: string) {
const headers = new Headers({'Content-Type': 'application/json'});
return this.http.get('https://voting-app-10.herokuapp.com/user/'+userID,{headers: headers})
.map(response => response.json())
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
});
}
ROUTE (BACKEND)
router.patch('/vote/:id', function (req, res, next) {
var decoded = jwt.decode(getToken(req));
Poll.findById(req.params.id, function (err, poll) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!poll) {
return res.status(500).json({
title: 'No Poll Found!',
error: {poll: 'Poll not found'}
});
}
poll.title = req.body.title;
poll.choice1 = req.body.choice1;
poll.choice2 = req.body.choice2;
poll.counter1 = req.body.counter1;
poll.counter2 = req.body.counter2;
poll.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
poll: 'Updated poll',
obj: result
});
});
});
});
router.patch('/:id', function (req, res, next) {
var decoded = jwt.decode(getToken(req));
Poll.findById(req.params.id, function (err, poll) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!poll) {
return res.status(500).json({
title: 'No Poll Found!',
error: {poll: 'Poll not found'}
});
}
if (poll.user != decoded.user._id) {
return res.status(401).json({
title: 'Not Authenticated',
error: {poll: 'Users do not match'}
});
}
poll.title = req.body.title;
poll.choice1 = req.body.choice1;
poll.choice2 = req.body.choice2;
poll.counter1 = req.body.counter1;
poll.counter2 = req.body.counter2;
poll.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
poll: 'Updated poll',
obj: result
});
});
});
});
Okay, at first your radio buttons don't get disabled, because you don't update the votes-array in your poll.component.ts after saving a vote.
I'm not sure if it's a good solution or not:
In your poll.service.ts:
voteOn(pollID: string, userID: string, choice: number) {
var user;
return new Promise((resolve) => { //Create a new promise to wrap the Subscriptions
this.http.get('http://localhost:3000/user/' + userID)
.map(response => response.json())
.subscribe(
json => {
user = JSON.parse(json);
if (user.votes == undefined) {
...
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error);
}).subscribe(() => {
resolve(user.votes); // <- Resolve your promise
})
}
)
});
}
And in your poll.component.ts:
voteOn(...).then((votes) => {
this.votes = votes; // To update your votes array
this.updateVote();
})
And I don't recommend to call functions in bindings, because it happens that the functions are called very often "to detect changes", like in your components.
So I would change the code in following way:
In your poll.component.ts:
vote:any //Added to your poll component
updateVote() {
this.vote = this.votes.find((vote) => {
return vote.pollID === this.poll.pollID;
});
}
You need to call this method in your ngOnInit method:
this.pollService.voted(localStorage.getItem('userId')).subscribe(
data => {
var result = JSON.parse(data);
this.votes = result.votes;
this.updateVote(); // <- To select the vote of this poll
},
err => { console.log("NGONINIT ERROR: " + err) },
() => { }
);
And in your poll.component.html:
<fieldset [disabled]="vote">
{{ poll.counter1 }} votes <input type="radio" id="{{ poll.choice1 }}" name="my_radio" value="{{ poll.choice1 }}" (click)="onChoice1(form)" [checked]="vote?.choice == 1"> {{ poll.choice1 }}
<br>
{{ poll.counter2 }} votes <input type="radio" id="{{ poll.choice2 }}" name="my_radio" value="{{ poll.choice2 }}" (click)="onChoice2(form)" [checked]="vote?.choice == 2"> {{ poll.choice2 }}
</fieldset>
But if you don't want to change your code in such a way, please tell me, so i can provide another solution.