I have made this react form and want to send the candidate object to the backend express server where I want to console log the candidate object. I have checked that form is taking the input properly. I am using axios to send a post request to the express backend.
import React, { Fragment, useState } from "react";
import axios from "axios";
const Form = () => {
const [candidate, setCandidate] = useState({
fullName: "",
phoneNumber: 0,
email: "",
gitProfile: "",
linkToResume: "",
designation: "",
interest: "",
});
const onChange = e =>
setCandidate({ ...candidate, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
});
};
const designationOptions = [
"--select option--",
"Graphic Designer",
"Full Stack Developer",
"Project Manager",
"SEO and Digital Marketing",
];
return (
//form input code
);
};
export default Form;
This is the backend express server code.
const express = require("express"),
bodyParser = require("body-parser");
(app = express()), (port = process.env.PORT || 5000), (cors = require("cors"));
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.get("/", function (req, res) {
console.log(req.body);
});
app.listen(port, () => console.log(`Backend server live on ${port}`));
I want to send the candidate object and console.log the object but I am getting a 404 error.
I have this setup in two different folders under a parent directory.
You are using app.get while sending request with axios as POST.
Try switching app.get to app.post
Related
I want to send data from my backend side with nodejs to my frontend side when I use fetch in the frontend side, I use reactjs.
and I get an error of "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" in the fetch function in useEffect function.
import { useEffect, useState } from "react";
import Item from "./item";
import style from "./show-item.module.css";
const ShowItem = (props) => {
const [orders, setOrders] = useState([]);
useEffect(() => {
fetch("/")
.then((res) => {
if(res.ok){
console.log('ok')
return res.json()
}
}).then(result => console.log(result))
.catch((err) => console.log(err));
}, []);
return (
<ul className={style["ul-item"]}>
{orders.map((item) => (
<Item
key={item.id}
id={item.id}
name={item.name}
detail={item.detail}
price={item.price}
amount={1}
/>
))}
</ul>
);
};
export default ShowItem;
I used in proxy in my react js app in package.json
"proxy": "http://localhost:5000",
this is my backend code
const adminRouts = require('./routes/admin');
const shopRouts = require('./routes/shop');
const shefRouts = require('./routes/chef');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 5000;
app.use('/admin',adminRouts);
app.use('/shef', shefRouts);
app.use(shopRouts);
console.log('listen ', port)
app.listen(port);
my shaf code
const express = require("express");
const router = express.Router();
const order = [
{
id: 1,
name: "הלחם שלנו",
detail: "לחם פראנה באפייה מסורתית,שמן זית ומטבלים טעימים",
price: 26,
},
];
router.use("/", (req, res, next) => {
console.log('here');
res.json(order);
});
module.exports = router;
HTML Is being returned, Signifying the wrong API route being called
First of all, it is worth noting that the backend is responding with HTML. Why is that? If you check in your express code there is no route where HTML is sent. The URL that you are using the fetch is '/'. This '/' route will get the base URL of 'localhost:5000' and nothing else. It seems that you are doing a request to the same URL that React is hosted in. This means that you are doing a get request to the 'public/' folder in the react app, and it is returning the HTML in the default 'index.html' that react uses.
You will need to change either the react proxy or the base URL for the server. I recommend changing all the API routes to be appended to '/api'. So the '/shef' becomes '/api/shef'. To make it dynamic make an API router with endpoint '/api' and move '/shef' to the API router file.
Although there are many ways to do this, here is one way:
make a 'api.route.js' file in the '/routes' folder
const router = require("express").Router();
const shopRouts = require('./routes/shop');
const shefRouts = require('./routes/chef');
router.get("/", async (req, res, next) => {
res.send({ message: "Ok api is working 🚀" });
});
router.use('/admin',adminRouts);
router.use('/shef', shefRouts);
router.use('/shop', shopRouts);
module.exports = router;
shaf code
const apiRoutes = require('./routes/api');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 5000;
app.use('/api', apiRoutes);
console.log('listen ', port)
app.listen(port);
Then in your frontend:
The only line changed here is:
Use which ever method you like to get the base URL. You might want to keep it in a .env file.
fetch(window.location.origin + "/api/shef")
import { useEffect, useState } from "react";
import Item from "./item";
import style from "./show-item.module.css";
const ShowItem = (props) => {
const [orders, setOrders] = useState([]);
useEffect(() => {
fetch(window.location.origin + "/api/shef")
.then((res) => {
if(res.ok){
console.log('ok')
return res.json()
}
}).then(result => console.log(result))
.catch((err) => console.log(err));
}, []);
return (
<ul className={style["ul-item"]}>
{orders.map((item) => (
<Item
key={item.id}
id={item.id}
name={item.name}
detail={item.detail}
price={item.price}
amount={1}
/>
))}
</ul>
);
};
export default ShowItem;
I'm building a React-Node app to consume QuickBooks APIs using OAuth 2 authentication. The app is structured so that the react app runs off a dev server at localhost:3000, and proxies http requests to the express server at localhost:3001.
So, I'm having some trouble making API calls: the react component responsible for rendering API data is crashing, and I'm getting the following error
"Missing required parameter: access_token"
I have the following code in my express server, which converts the authorization code into an access token, and then (I think) passes that token to http://localhost:3000/companyInfo. However I suspect this is where the problem is - is the token actually being sent to this address, or have I misunderstood how OAuth works? Here's the server-side code in question:
app.get("/callback", function (req, res) {
oauthClient
.createToken(req.url)
.then(function (authResponse) {
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
})
.catch(function (e) {
console.error(e);
});
res.redirect("http://localhost:3000/companyInfo" );
});
...here's my entire server:
const express = require("express");
const OAuthClient = require("intuit-oauth");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const port = process.env.PORT || 3001;
let urlencodedParser = bodyParser.urlencoded({ extended: true });
let oauth2_token_json = null;
let oauthClient = null;
app.get("/authUri", urlencodedParser, (req, res) => {
oauthClient = new OAuthClient({
clientId: "****",
clientSecret: "****",
environment: "sandbox",
redirectUri: "http://localhost:3001/callback",
});
let authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting],
state: "testState",
});
res.send(authUri);
});
app.get("/callback", function (req, res) {
oauthClient
.createToken(req.url)
.then(function (authResponse) {
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
})
.catch(function (e) {
console.error(e);
});
res.redirect("http://localhost:3000/companyInfo" );
});
app.get("/getCompanyInfo", (req, res) => {
let companyID = oauthClient.getToken().realmId;
let url =
oauthClient.environment == "sandbox"
? OAuthClient.environment.sandbox
: OAuthClient.environment.production;
oauthClient
.makeApiCall({
url: url + "v3/company/" + companyID + "/companyinfo/" + companyID,
})
.then(function (authResponse) {
console.log(
"The response for API call is :" + JSON.stringify(authResponse)
);
res.send(JSON.parse(authResponse.text()));
})
.catch(function (e) {
console.error(e);
});
});
app.listen(port, () => {
console.log(`Server is listening on port: ${port}`);
});
...and here's the react component where I want to render the returned API call data:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const CompanyInfo = () => {
const [ info, setInfo ] = useState('')
useEffect(() => {
axios.get('/getCompanyInfo')
.then(res => setInfo(res.data))
},[])
return(
<div>
<p> {info.CompanyInfo.CompanyName} </p>
</div>
)
}
export default CompanyInfo
The strange this is that sometimes I have been able to render the API call data in this component, but I can only do it once. If I refresh my page, it crashes, and I have to start the login process again in order to make the API call work.
Hi I'm trying to upload a file to a server send with axios. To send it I use react with Hooks and UseState, the thing is that when I do the console.log of the file in de frontend it shows all correctly but when I send it to backend I recive it empty.
Here is an example about what shows the frontend with console.log():
Here is the function I use to send the 3 files to backend and the differents things like react Hooks and that which I need:
const [weight, setWeight] = useState("");
const [frontPhoto, setFrontPhoto] = useState({});
const [sidePhoto, setSidePhoto] = useState({});
const [backPhoto, setBackPhoto] = useState({});
const JWT = new ClassJWT();
const axiosReq = axios.create();
const [uploadErrors, setUploadErrors] = useState([{}]);
const upload = async (e) => {
e.preventDefault();
await JWT.checkJWT();
console.log(frontPhoto);
axiosReq.post("http://localhost:3001/upload-progress", {
weight,
frontPhoto,
sidePhoto,
backPhoto,
token: JWT.getToken()
}).then((response) => {
console.log(response);
if (response.data.statusCode === '200') {
} else {
}
});
};
And then, in the backend de console.log() is like this:
{
weight: '70',
frontPhoto: {},
sidePhoto: {},
backPhoto: {},
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjI2NTk3Mjg1LCJleHAiOjE2MjY1OTgxODV9.njDz7BZX57NvAK399abQLhoelpTS4kStj4LBzjw5gR8'
}
Here is the router code I use to this upload:
routerProgress.post("/upload-progress", verifyJWT, async (req, res) => {
console.log(req.body);
}
And here is all the server configuration:
import express from 'express';
import sequelize from './db/db.js';
import cors from 'cors';
import fileUpload from 'express-fileupload';
// SERVER CONFIGURATION
const app = express();
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Listening at ${PORT}`);
sequelize.sync({ force: false })
.then(() => console.log('Database Connected!'))
.catch(err => console.log(err));
});
// BODYPARSER
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000}));
app.use(cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true
}));
app.use(fileUpload({
createParentPath: true
}));
// ROUTES
import { routerAuthentication } from './routes/authentication.js';
import { routerProgress } from './routes/progress.js';
app.use(routerAuthentication);
app.use(routerProgress);
I don't know how to solve it, I tried many things but anything doesn't word. Please if anyone know what can I do to solve it, I'll be very grateful with him. Thanks!
I have a C# app that does a POST with json to http://localhost:9090/myend
{
"eqid": "123",
"cnid": "123",
"report":{
"somevalue": "123",
"anothervalue": "123
}
I have react app that runs on port 3001
And I have express running on port 9090
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 9090
app.use(bodyParser.json())
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
app.post("/myend", (req, res) => {
console.log(JSON.stringify(req.body, null, 4))
res.status(200).end() // Responding is important
})
I can see that post in console in the express but how do I get that json in react app? Do I even need express?
res.end([data] [, encoding])
Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
use res.send
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 9090
app.use(bodyParser.json())
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
app.post("/elsdcp", (req, res) => {
console.log(JSON.stringify(req.body, null, 4))
res.status(200).send(req.body)
})
You can also use res.json.
in react App
use fetch or axios
for example
// fetch
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request Example' })
};
fetch('https://stackoverflow.example.com/fetch/post', requestOptions)
.then(response => this.setState({ articleId: response.data.id }));
// axios
const article = { title: 'React POST Request Example' };
axios.post('https://stackoverflow.example.com/fetch/post', article)
.then(response => this.setState({ articleId: response.data.id }));
I'm setting up a local backend server with node, and I'm trying use fetch to get values to render in my frontend react app. I've gotten most of the way, as everything compiles, however I'm running into issues with fetching the correct values. Or at least, I think I'm doing everything correctly.
The goal is to use fetch() in my app.js to get render values from route foo in server.js.
I can get a response from /foo but it is not what I was sending. I was sending a json object {text: "Foo"}
However, I'm receiving this in the console: App.js:12 Response {type: "basic", url: "http://localhost:3000/foo", redirected: false, status: 200, ok: true, …}
Any idea what I'm doing wrong?
Am I not fetching or sending objects correctly between routes? How can I get "Foo" to render on the line <p>The current state is {this.state.message}</p> in
'App.js`
Here is my app.js:
import React, {Component} from 'react';
import './App.css';
class App extends Component {
state = {
message: ""
};
componentDidMount() {
fetch('/foo')
.then(res => {
console.log(res);
return res.json();
// .then(express => this.setState({ express }))
// .then(() => console.log(this.state.message));
});
}
render() {
return (
<div className="App">
<h1>Users</h1>
<p>The current state is {this.state.message}</p>
</div>
);
}
}
export default App;
Here is my server.js:
const express = require('express');
const users = require('./routes/users');
const foo = require('./routes/foo');
const app = express();
const port = process.env.PORT || 8080;
// Set a route for when commands are processed for users
app.use('/users', users);
app.use('/foo', foo);
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.listen(port, () => console.log(`Listening on port ${port}`));
Here is my foo.js
let express = require('express');
let router = express.Router();
router.get('/', function(req, res) {
res.send([{text: "Foo"}]);
});
router.post('/', function(req, res) {
res.send('POST handler for /foo route.');
});
module.exports = router;
the res.json() is still returning a promise, try this out:
componentDidMount() {
fetch("/foo").then(res =>
res.json().then(data => {
console.log("data", JSON.stringify(data, null, 4));
// here you can set state
//...
})
);
}