Frontend and backend url not matching - reactjs

I have a problem with matching routes. I am runnning react app on port localhost:3000, and node/express server is running on port localhost:3001.
I am trying to create a club by firing this request on the frontend:
async addClub(club) {
try {
let postData = await fetch(`${this.backendUrl}/club`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({...club}),
});
this.backendUrl is correctly imported
Route on the backend file is:
router.post('/club', async (req, res) => {
try {
const body = req.body;
await new Club(body).save((err, club) => {
if (err) return console.log(err)
console.log('New club created');
res.status(200).send({ msg: 'Club created' });
});
} catch(err) {
res.status(400).json({
msg: 'Bad Request'
})
}
})
But for some reason frontend execution cannot find route specified on the backend.
I get an error: POST http://localhost:3001/club 404 (Not Found)
I have other routes through which I create other things and they work perfectly.

Related

Axios Post from react to express proxy server

I have created an express server in which I am implementing a graphQL request. The following block of code was taken from postman snippets of a successful request
const express = require("express"),
app = express(),
port = process.env.PORT || 4000,
cors = require("cors");
var axios = require('axios');
var data = JSON.stringify({
query: `mutation claimTask ($taskId: String!, $assignee: String) {
claimTask (taskId: $taskId, assignee: $assignee) {
id
name
taskDefinitionId
processName
creationTime
completionTime
assignee
variables {
id
name
value
previewValue
isValueTruncated
}
taskState
sortValues
isFirst
formKey
processDefinitionId
candidateGroups
}
}`,
variables: {"taskId":"22","assignee":"demo"}
});
var config = {
method: 'post',
url: 'http://[my_ip]/graphql',
headers: {
'Authorization': 'Bearer ey....',
'Content-Type': 'application/json',
'Cookie': 'TASKLIST-SESSION=..'
},
data : data
};
app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));
app.post("/api", (req, res) => {
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
res.send({ message: JSON.stringify(response.data) });
})
.catch(function (error) {
console.log(error);
res.send({ message: error });
});
})
Currently I am calling this request from a react app with a button like this:
Axios({
method: "POST",
url: "http://localhost:4000/api",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
For the next step I want to pass the variables from my react app instead of writing them directly as string to express. What is the right approach to achieve this?
I am using the express server to avoid cors related issues.
Any suggestions can be useful, thank you!
So you want to send an Axios POST from react. Something along those lines should work:
const handleSubmit = (e) => {
e.preventDefault();
const variables = {
taskId: ”22”,
userId: “demo”
};
axios.post("http://localhost:4000/api", variables).then((response) => {
console.log(response.status);
});
};
Inspired by https://blog.logrocket.com/understanding-axios-post-requests/

CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function

I'm posting data to a DynamoDB table with axios in a React front-end.
The API is set up through a serverless configuration with an API Gateway and Lambda on AWS.
While the request goes through and I see the added item on the database I still get a CORS error https://i.stack.imgur.com/m7yMG.jpg
This is the axios method:
import axios from "axios";
export const sendItemToDB = async (_data) => {
if (!_data) { return };
try {
const res = await axios({
method: "POST",
url: process.env.REACT_APP_QUERY_API,
data: _data,
headers: {
"Content-Type": "text/plain"
},
});
console.log("data returned from api", res);
} catch (error) {
console.log("Error sending File to db: ");
console.log(error);
}
};
And the API method on Lambda:
const createRecord = async (event) => {
const response = { statusCode: 200 };
try {
const body = JSON.parse(event.body);
const params = {
TableName: process.env.DYNAMODB_TABLE_NAME,
Item: marshall(body || {}),
};
const createResult = await db.send(new PutItemCommand(params));
response.body = JSON.stringify({
message: "Successfully created record.",
createResult,
});
} catch (e) {
console.error(e);
response.statusCode = 500;
response.body = JSON.stringify({
message: "Failed to create record.",
errorMsg: e.message,
errorStack: e.stack,
});
}
return response;
};
I based this configuration on this tutorial : https://github.com/jacksonyuan-yt/dynamodb-crud-api-gateway
I solved this following amazon documentation and reconfiguring the serveless deployment yml.
Serverless documentation on api gateway and lambda proxy integration here
Adding the missing headers to all lambda functions was essential.
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
};
Also testing that OPTIONS is working for the preflight:
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-test-cors.html
Just as Stavros noticed, the problem is that this is not a simple cross-origin POST method request (because it contains custom headers), so you need to tweak CORS settings of AWS API Gateway by adding
"POST, GET & OPTIONS" for Access-Control-Allow-Methods
"content-type" for Access-Control-Allow-Headers
You can do it through console like this
You also might need to add those headers in lambda like this
and it will work.

Getting a POST 404 error on back-end server (MERN STACK)

I'm attempting to send a complete form to back-end server (decoupled MERN application in localhost).
The request is reaching the server, but not posting to the database.
This is seen in server console...
POST /contracts 404 1.371 ms - 19
The data to be sent in form is logging in console as an object (as intended).
This is the service function making post request from the frontend to the backend ...
const BASE_URL = `${process.env.REACT_APP_BACKEND_SERVER_URL}/contracts`
export const createContract = async (formData) => {
try {
const res = await fetch(BASE_URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${tokenService.getToken()}`
},
body: JSON.stringify(formData)
})
return await res.json()
} catch (error) {
console.log(error)
throw error
}
}
this is the backend routes... (already set up as /contracts in server.js)
import { Router } from 'express'
import * as contractsCtrl from '../controllers/contracts.js'
const router = Router()
router.post('/', contractsCtrl.create)
router.get('/all', contractsCtrl.index)
export { router }
create controller function on the backend...
function create(req, res) {
console.log(req.body)
Contract.create(req.body)
.then(contract => res.json(contract))
.catch(err => res.json(err))
}
Any help you have would be appreciated!!

Cant post with axios network error reaxt native to heroku

I made a flask backend and deploy to heroku. It is working when i made a get request and made a post with postman json data. But i cant post when i use axios or fetch in react-native app.
const url = 'https://test.herokuapp.com/list/add';
const config = {
headers: { 'content-type': 'application/json' },
data: {
"test":this.state.testdata
},
};
const response = await axios.post(url, config)
.then(function(res){
console.log(res)
})
.catch(function(error) {
console.log('What happened? ' + error);
}); ```

React app can't get data from ExpressJS API

I've run into issue where I can't get confirmation that user is authenticated from ExpressJS backend. I am using PassportJS with Google OAuth2.
When I try to access my API endpoint through browser, it returns the data I need. Why is this so? Is there a problem with cors and backend or with my request?
This is the error I get after a while on the same page: GET http://localhost:5000/api/auth/login/success net::ERR_EMPTY_RESPONSE
Here is my request:
useEffect(() => {
const fetchData = async () => {
await axios
.get(`${API_URL}/auth/login/success`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
})
.then((response) => {
if (response === 200) {
console.log(response);
console.log("200");
return response.json();
}
throw new Error("Failed to authenticate the user.");
})
.then((responseJson) => {
userHasAuthenticated(true);
setUser(responseJson.user);
console.log("responseJson");
setLoading(false);
})
.catch((error) => console.log(error));
};
fetchData();
}, [loading]);
I dont't get any outputs to the console.
Here is my route on the backend:
router.get("/login/success", (req, res) => {
console.log(req.user);
console.log("/login/success");
if (req.user) {
res.json({
success: true,
message: "User has successfully authenticated.",
user: req.user,
cookies: req.cookies,
});
}
});
When I try to access this route on my browser, I see the response and it prints it out in the console. But when I visit the frontend page from where the request is sent, nodejs console prints out undefined.

Resources