I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);
Related
I am getting the you need to enable javascript to run this app error in my MERN stack application. Everything else works fine except for an api call I made for a particular route. I use axios package and all API calls I made in the application are working fine and fetching required data and displayed on my browser. The problem is this particular route. This same route works fine in postman. Here is the code:
useEffect(()=>{
const fetchMenu = async () =>{
try{
const response = await axiosPrivate.get(`/api/v1/menu`, { withCredentials: true,headers:{authorization: `Bearer ${auth}`}
});
console.log(response.data, 'hello menu')
}catch(err){
}
}
fetchMenu()
}, [])
If I call the API via postman, it is fetching the data fine. AxiosPrivate is coming from axios and has been working fine in all places I used it. I really don't know what could be the problem.
The problem was with how I was calling my api. The address should have been /v1/menu instead of /api/v1/menu. This is because in my package.json file already has the proxy this way "proxy": "http://localhost:5000/api/v1",
I have a NodeJS/Express application.
From an url endpoint titled: localhost:3000/form?someProp=someValue&somethingElse=someOtherValue
This page submits a form to another Express endpoint.
I submit to an Express POST endpoint. I know in a GET endpoint I could access the query params via req.query, but I cannot seem to do that in a POST request.
Is there a way to access the query params from the request in a POST route?
(other than splicing the header.referrer... which I may just have to do)
Here are some code snippets:
If I submit to the first route it works, if I submit to the second... it does not.
router.get('/test',
(req, res) => {
console.log(req.query); // {someProp: someValue, somethingElse: someOtherValue }
}
);
router.post('/test2',
(req, res) => {
console.log(req.query); // returns {}
}
);
So I tried to send a simple request to test it and got everything working without doing anything special (The only thing extra I have is that I'm using body-parser middleware from npm):
app.use(bodyParser.json({limit: '50mb'}));
Then I tried this simple route and got the result query params as you can see in the picture attached.
http://localhost:8080/test?test=1&what=2
Any chance you're sending the other form request from the client in a different way? try looking at the network in chrome and see if you sending what you expecting. Obviously, there is something missing here as it worked for me without doing anything special.
I've implemented the "sign in with Facebook" authorization method for my Express.js Node app. Since the app is hosted in the EU, Facebook requires it to have a data deletion request callback URL.
I've created an endpoint for the data deletion request, but whenever I make Facebook call that endpoint both req.body and req.query are empty - if I've understood correctly the body should contain a signed_request that could be used to e.g. verify the caller.
My CORS settings should be fine and I've tested my endpoint by calling it from Postman. The endpoint is able to receive a POST request with a JSON body without any problem.
So, what am I doing wrong - why does it seem like Facebook is calling my endpoint with a POST request that has an empty body?
My endpoint:
import express from 'express'; // 4.17.1
const router = express.Router();
router.post('/fb_data_deletion', (req, res, next) => {
console.log(req.body); // {}
console.log(req.query); // {}
if (!req.body || !req.body.signed_request) {
console.log('Bad request'); // Ends up here whenever Facebook calls this route
return req.sendStatus(400);
}
// verify request, delete user's data + other code here
});
Turns out Facebook isn't sending a POST request that uses Content-Type application/json but application/x-www-form-urlencoded.
To get the body of Facebook's POST request I had to add the following line to my app.js where the Node server is being set up:
app.use(express.urlencoded());
Im new in backend development (using NodeJs Express).
Its very basic question (I didn't find any good tutorial about it)
Question is:
I have this line of code:
app.get('/test', function (req ,res){
res.send('test');
});
What I wanna do is: BackEnd only sends res to FrontEnd, if FrontEnd send some JSON first.
Like Backend will show Something to FrontEnd, only if FrontEnd send JSON first;
How to handle it? What code to write?
Or what to type in google search to find this kind of tutorial
You are building a REST API with node. In REST we don't keep states. When we receive a request we process and respond. In the Front end, you can do wait until the response is received. use promises, async-await or callbacks to wait until the response in the Front end. Use these methods to connect with back end from front-end axios, fetch. To process the incoming JSON body use body-parser. Based on the request body you can process and send the response. PS: Every request should be given a response. That's how REST behaves.
In Query
yourbackend.com/test?message=welcomeToStackOverflow
This is how you can access with in query:
const {message} = req.query;
console.log(message);
// welcomeToStackOverflow
In Params
yourbackend.com/test/:message
This is how you can access with in params :
const {message} = req.params;
console.log(message);
// welcomeToStackOverflow
Here you have working example : https://codesandbox.io/s/trusting-rosalind-37brf?file=/routes/test.js
I made a form post request from my react front end. In my express route I handle it, and I send the data to the browser, as such:
app.post("/api/fetchuser", async (req, res) => {
// Doing some stuff here
res.send(req.body.user);
});
My question is: How can I get the data from this POST request route back to my client side? Previously, I did axios.get(...) to retrieve data on a app.get(...) route in a similar fashion, however, this is a POST route. How can I solve this issue?
Just do axios.post request. See Performing a POST request section of axios documentation.
Edit: Yes you can also retrieve data by POST request. You don't have to post any data to the server while performing the request.
axios.post('/api/fetchuser/',{})
.then(res => console.log(res.data));