I'm trying to make a post request to the server,but it returns 400 error.
:
this is react function
const handleSubmit = () => {
const bookInstanceObject = {
imprint: imprint,
};
axios
.post('http://localhost:3001/catalog/bookinstance/create', bookInstanceObject)
.then(res => {
console.log(res.data);
})
.catch(error => {
console.log(error);
});
};
and this is the server side:
router.post('/bookinstance/create', (request, response, next) => {
const body = request.body;
const bookInstance = new BookInstance({
imprint: body.title,
});
bookInstance
.save()
.then(savedBook => {
response.json(savedBook.toJSON());
})
.catch(error => next(error));
});
any idea ?
What I think is happening
The front end's handleSubmit function is POSTing to /catalog/bookinstance/create, while the server is expecting it to come to /bookinstance/create.
Simple typo, easy to miss when your stressing over it not working.
How to fix?
Change the URLs to match.
Either:
change the front-end's POST url to /bookinstance/create,
or:
change the server's expected route to router.post('/catalog/bookinstance/create',
Why is it a GET in the error log?
I don't know but I suspect that this error is about a GET request somewhere else in your code.
Please let us know in the comments if the error goes away with this fix. (Assuming my fix works)
Related
I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
Here is my code :
const axios = require('axios');
const AxiosLogger = require('axios-logger');
const instance = axios.create();
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
console.log(response.data);
return response.data
})
.catch(error => {
console.log(error);
});
});
};
I would suggest trying response.send to forward the axios response to your client like so:
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
// Send the axios response to the client...
res.send(response.data)
})
.catch(error => {
console.log(error);
});
});
};
hi guys im fairly new to node.js and I was wonder if I am making a call twice that I am unaware of. I am getting a Error: Can't set headers after they are sent.
export const hearingReminder = functions.https.onRequest((request, response) => {
console.log(request.body)
const payload = {
notification: {
title: 'Upcoming Hearing',
body: 'You have a hearing in one hour.',
}
};
const fcm = request.body.fcm
console.log(request.body.fcm)
try {
response.status(200).send('Task Completed');
return admin.messaging().sendToDevice(fcm, payload);
} catch (error) {
return response.status(error.code).send(error.message);
}
Your code is attempting to send a response twice, under the condition that admin.messaging().sendToDevice generates an error. Instead of sending the 200 response before the call, only send it after the call. Sending the response should always be the very last thing performed in your function.
Your code should be more like this:
admin.messaging().sendToDevice(fcm, payload)
.then(() => {
response.status(200).send('Task Completed');
})
.catch(error => {
response.status(error.code).send(error.message);
})
Note that you don't need to return anything for HTTP type functions. You just need to make sure to handle all the promises, and only send the response after all the promises are resolved.
I am testing my NodeJS backend using Insomnia and while it does work no problem in Insomnia I am getting a 500 error on the frontend every time. I was wondering if anyone maybe knew where this could be coming from if like I said it works just fine on my the endpoint testing program. Since it is a 500 error it is not very descriptive. Links can be shared if needed
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://exampleapi/api/login")
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.access_token);
props.history.push("/");
})
.catch(err => console.log(err.response)); };
So I figured it out it was an error in my post request would should have been included was
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://mystery-doggo.herokuapp.com/api/login", creds)
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.payload);
props.history.push("/");
})
.catch(err => console.log(err.response));
};
"creds" after the link and change res.data.access_token to res.data.payload
I'm trying to make a POST request using axios to my firebase cloud-function on form submit in react app. But I get '500' error everytime I make a request with an html-page response This app works best with javascriot enabled.
Latest Update:
It looks like there is no issue with cloud function
code. Rather more of a react-component issue. I used Postman to send
the POST request with header prop Content-Type set to application/json
and sending body in raw format {"email": "example_email"} and got
expected response from the cloud function. But when sent the request from
react component above, I get an html file response saying the app
works best with javascript enabled
I've tried setting Content-Type to both Application/json and multipart/form-data as I suspected it to be an issue but still got no luck.
Following is my code for cloud function and react submit form:
Cloud Function
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true })
const runThisFunc1 = require(./libs/runThisFunc1);
const runThisFunc2 = require(./libs/runThisFunc2);
exports.wizardFunc = functions.https.onRequest((request, response) => {
cors(request, response, () => {
let email = request.body.email;
try {
return runThisFunc1(email)
.then(data => {
console.log("Word Done by 1!");
return runThisFunc2(data);
})
.then(res => {
console.log("Word Done by 2!");
return response.status(200).send("Success");
})
.catch(err => {
console.error("Error: ", err.code);
return response.status(500).end();
});
}catch(err) {
return response.status(400).end();
}
});
});
React-Form-Component Snippet
import axios from 'axios'
...
handleSubmit = e => {
e.preventDefault()
const { email } = this.state
axios({
method: 'post',
url: `${process.env.REACT_APP_CLOUD_FUNCTION_ENDPOINT}`,
data: { email: email },
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
.then(res => {
//do something with reponse here
})
.catch(error => {
console.error(error)
})
}
...
Is there something wrong I am doing in the code or the request config is wrong?
I'm currently developing a 'Dupe Finder' web app for a co-worker. This is my first time using the 'csvtojson' package.
I'm reading from the file just fine on the server, but when I send a response back to the client (ideally containing a json object) I'm getting this very odd console log and I'm not sure if its correct:
To get this response, I have a button on the home page, when clicked, the client makes an http request on the home directory of the server, called '/getnums'. The request reads from the CSV then should be returning and obj with its contents. It is sort of doing that, in the screenshot, if I click the tick next to promiseValue, it'll give me an array. But i'm not sure why its returning a Promise..anyway..
api.js:
var CSVDATA = () => {
fetch('/getnums')
.then(res => {
console.log(res.json())
})
}
export default {
CSVDATA,
}
'/getnums' goes to my router, which is simly router.get('/', mainController.getNums)
in the controller is where the reading begins:
const csv = require('csvtojson')
module.exports = {
getNums: (req, res, next) => {
const csvFilePath = `${__dirname}/../../client/readFrom/main.csv`
csv().fromFile(csvFilePath)
.then(jsonObj => {
return res.status(200).json(jsonObj)
})
.catch(e => {
req.error = e
next()
})
},
}
anyone have an idea what might be going on here?
That is simply how .json() works.
It returns promise so you need to handle it asynchronously
var CSVDATA = () => {
fetch('/getnums')
.then(res => res.json())
.then(json => console.log(json));
}
export default {
CSVDATA,
}
MDN link