Fetch post without refreshing - Vanilla JavaScript and Express.js - javascript

I'm making a Express.js app which has a form to send contact info to a mail address with a post function. I'm using a "front-end post" because if I do it entirely from the backend I need a route to go after the post.
I want to post the info without refreshing the page, but I can't make it.
My front-end code:
formButton.addEventListener("click", ()=>{
fetch('http://localhost:3000/contact', {
method: 'POST',
body: JSON.stringify({
nombre: form.elements["nombre"].value,
email: form.elements["email"].value,
consulta: form.elements["consulta"].value
}),
headers:{
'Content-Type': 'application/json'
}
}).then(response=>{
if(response.ok){
return response.json;
}
throw new Error('Request failed');
}, newtworkError => console.log(networkError.message)
).then(jsonResponse =>{
console.log(jsonResponse);
});
});
And the server side code to handle the request is:
app.post('/contact', (req,res)=>{
sendMail(req.body.nombre, req.body.email, req.body.consulta);
});
The mail is sent with the sendMail function using nodemailer, and it works, but after execute the function the page refreshes and in the url bar appears the url "http://localhost:3000/?nombre=XXX&email=XXX%40XX&consulta=XX".
How can I do the post without refreshing?

Related

Axios auth request web site

I am trying to enter a website by submitting login data with axios. But each time the response.data is the site's login html page. When I want to access the site and get the data from my profile. How can I solve? how do i get the cookie token?
This is my code. Where i wrong?
await axios.post('https://namesiteweb.com/login.html',
{
'username': 'username',
'password': 'password'
}
).then(response => {
console.log(response);
}).catch(err => {
console.log(err);
});

Axios POST request returns 404 error when sending to Node.js API

I am developing a web application using a React frontend and a Node.js backend. The frontend sends a POST request to the backend using Axios like this:
Register.js
...
handleSubmit = (e) => {
e.preventDefault();
const { email, password, name, dateofbirth } = this.state;
const user = { email, password, name, dateofbirth };
const url = "http://localhost:9000/register";
axios
.post(url, user, {
headers: {
"Content-Type": "application/json",
},
})
.then((response) => console.log(response))
.catch((error) => {
console.error("You have made a big error. " + error);
console.log(user);
});
};
...
While the backend receives the request like this:
./routes/register.js
...
router.post("/register", async (req, res) => {
console.log("Inside Home Login");
res.writeHead(200, {
"Content-Type": "application/json",
});
console.log("Users : ", JSON.stringify(users));
res.end(JSON.stringify(users));
})
...
However I get the error "POST http://localhost:9000/register 404 (Not Found)" upon trying to send anything.
My guess would be that you are routing in your index.js. If you can provide a code sample to figure it out.
If so, the thing is defining a routing like,
app.use('/register', yourImportedVariable);
does define a route at http://localhost:9000/register.
So, if in your routes/register.js file you define a GET endpoint with '/register' your front-end call must be http://localhost:9000/register/register
To fix it, either rename your route as '/', or fix your front-end call with the above url.

How do I make a post request from a react front-end to a node back-end? Getting 404

I'm trying to make a simple website where users can post things to learn the MEAN stack. When I'm handling the POST request, which will be handled and inputed to the MongoDB server through the back-end. React is on port 3000, and the server is on 5000. How do I make the request go from 3000 to 5000? My request works through Postman but not using axios. I added the proxy to the client-side package.json.
I've tried changing the proxy, adding CORS, changing to every single possible route. Nothing works.
Back-end:
router.post('/api/req',(req,res)=>{
const newPost = new Post({
title: req.body.title,
description: req.body.description
})
newPost.save().then(()=>{
console.log('Item added to database!')
});
})
Front-end:
axios({
method: 'post',
url: '/api/req',
data: {
title: this.state.title
},
validateStatus: (status) => {
return true;
},
}).catch(error => {
console.log(error);
}).then(response => {
console.log(response);
});
"proxy": "http://localhost:5000/" - package.json
I'm expecting the POST request to go through, and for the title to be inputed into the database. Instead, I get the error: Failed to load resource: the server responded with a status of 404 (Not Found)
The error is coming from localhost:3000/api/req, and it should be proxying port 5000. Also, the actual route is routes/api/req.js.
You will have to pass the complete url:
axios({
method: 'post',
url: 'http://example.com:5000/api/req',
data: {
title: this.state.title
},
validateStatus: (status) => {
return true;
},
}).catch(error => {
console.log(error);
}).then(response => {
console.log(response);
});

Spring: request body missing error when sent from client but works with postman?

I have a Spring Rest backend setup as well as a react client. Both are setup on different local ports. I am trying to send a simple request from my React client using a fetch call to my spring rest api.
When sending the POST request using Postman, the API responds as expected.
When sending the request from the React client I receive the following 400 error:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing: public
org.springframework.http.ResponseEntity<?>
I have done the following:
Disabled CSRF on my spring application.
Set global CORS config to accept all requests.
Ensured on multiple occasions that the request body is correct and identical to that sent via Postman.
Here is my Fetch request from react client:
fetch(API_BASE_URL + '/api/auth/signin', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Request-Method': 'POST'
}),
body: {
username: this.state.uname,
password: this.state.password,
}
}).then(
function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function (data) {
let json = JSON.parse(data);
let token = json.tokenType + " " + json.accessToken;
localStorage.setItem(ACCESS_TOKEN, token);
alert('successfully saved token:' + token);
});
}
)
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
For those interested:
The data passed in payload was of an incorrect format. While this may not appear logical, creating a variable as so:
let payload = {
username: this.state.username,
password: this.state.password,
};
And passing that as the body to fetch seems to work.
Hopefully this may help others facing the same problem..

How to make a POST request using CustomVision api with NodeJS

I'm trying attach an image using the bot emulator tool and sending this image off to the microsofts customvision api, the issue I'm having is that I get
{ Code: 'BadRequestImageFormat', Message: '' }
back from custom the custom vision api call.
I'm using the the request module from npm to handle the calls
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'xxx',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/octet-stream',
'Prediction-Key': 'xxx'
},
body: session.message.attachments[0]
}, function(error, response, body){
console.log(body);
});
}
});
I believe that I may be sending the wrong format through to custom vision however I have been unable to figure it out as of yet.
I replicated your issue and it looks like the problem is your 'Content-Type'. You're attempting to pass JSON in your request, but setting the content-type as octet-stream. See my modified code below:
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'https://northeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'Your API Key...'
},
body: session.message.attachments[0]
},
function (err, response, body) {
if (err) return console.log(err)
console.log(body);
});
}
});
When I run this, I get the error InvalidImageUrl which is to be expected as it's looking for a content on localhost. You could get round this by exposing your localhost using Ngrok.

Categories

Resources