I am getting error when I fetch Data from my backend? - javascript

I am running my backend on "http://localhost:3001/" using expressjs
app.listen(3001, function() {
console.log('Server is running');
});
my frontend on "http://localhost:3000/" using react but when i fetch data I am getting an error
package.json
"proxy": "http://localhost:3001",
componentDidMount() {
const fetchData = async () => {
fetch('/data')
.then(res => res.json())
.then(d => console.log(d));
};
fetchData();
}
here is the error

Your proxy in the package.json file on the client should be set to whatever server you are trying to connect to on the backend:
package.json
"proxy": "http://localhost:3001",

Does the "/data" route exist?
If it doesn't, you're trying to extract JSON from a html file and hence the error.
Remove .then(res => res.json()) until you define the route on your server.

Related

How to send data (a url string) in express to backend from frontend?

I am trying to build a wikipedia web scraper api and this is my code:
const app = express()
const port = 3000
const url = "https://en.wikipedia.org/wiki/Yeti_Airlines_Flight_691"
axios.get(url).then(async (res) => {
try {
if (res.status == 200) {
const result = // Doing cheerio stuff here
app.get('/', (req, res) => {
res.status(200).send(result)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
}
} finally {
//
}
});
How can I send url dynamically to backend using express and do some stuff then send result back to frontend?
Client side:
This is a function you define in your frontend. You set a request link, which must be known here on client side and server side. Thus take something like /request. Then use axios to send a request to the server. You can pass any parameters with „dynamic“ Information as you called it. The server will receive these informations and can handle them.
const getData = () => {
// insert your server url here instead, with the /request at the end
const requestLink = `http://localhost:3001/request`;
axios
.get(requestLink, {
params: { url: "wikipedia.de/test123" },
})
.catch((error) => {
// here you can implement error handling
console.log(error);
})
.then((res) => {
// print result, received from the server
console.log(res);
});
};
Server side:
The backend is going to wait for a request to the defined link /request.
If he receives such a request, he is executing the code. The req variable contains your dynamic data, such as the wiki url.
Use res.json to send data back to your frontend.
app.get(`/request`, (req, res) => {
// do something with the request here
console.log(req.query);
// send result to the frontend
res.json({
status: "This could be an answer to the frontend.",
});
});

I can get response with postman but cannot get with axios

I started a full stack app. I wrote models and routers on backend part. On frontend part, I installed axios and add "proxy": "http://localhost:xxxx/api" to package.json file. When I send get request with postman, it response me the data. But when I go to http://localhost:xxxx, on chrome console it says "AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST'"
Its my package.json file's last line;
}, "proxy": "http://localhost:8800/api"
}
Its my get router;
router.get("/", async (req,res) => {
try {
const pins = await Pin.find();
res.status(200).json(pins);
} catch (err) {
res.status(500).json(err)
}
});
and its my frontend app.js useEffect code:
useEffect( () => {
const getPins = async () => {
try {
const res = await axios.get("/pins");
setPins(res.data);
} catch (err) {
console.log(err);
}
};
getPins();
}, []);
Thanks for helps
Instead of attempting to ping axios.get("/pins") try to ping axios.get("/")`
I believe you are getting a 404 not found on the route as your frontend and backend routes don't match.
I restarted Visual Studio Code and the problem solved.

Can't reach env from React Component in Next.js

I have a Next.js project. I have created .env file and using enviroments from this file in server.js file. But when I want to reach these enviroments from component, I can't access. What should I do?
This is .env file:
SERVER_PORT=3000
DOMAIN=127.0.0.1
DATABASE=dburl
This is server.js file:
require('dotenv/config')
const port = process.env.SERVER_PORT || 3000
server.listen(port, (err) => {
if(err) throw err
console.log(`Server listen on http://127.0.0.1:${port}`)
})
This is any component of react:
axios
.get(`http://${process.env.DOMAIN}/api/improve-language`)
.then(res => {
...
})
.catch(err =>{
console.log(err)
})
Based on the documentation if you want to use the env variables in the browser, they must be named with prefix NEXT_PUBLIC_.

Can't get axios to perform get without full url

Every time I try to use /bikes or /bikes/add in my axios requests, it never seems to connect. I always get something like this:
xhr.js:178 GET http://localhost:3000/bikes/ 404 (Not Found)
However, when I use the full url, like: http://localhost:4000/bikes/ it connects perfectly. I tried messing with the app.get in server.js, the get in my route file, and the actually axios.get in my bikes-list file to no avail.
Anyone have any ideas? This is part of a MERN app.
bikes-list.js(component) snippet:
componentDidMount() {
axios.get('/bikes/')
.then(response => {
this.setState({bikes: response.data});
})
.catch(function (error){
console.log(error);
})
}
server.js snippet:
app.use('/bikes', bikeRoutes);
bikes.js(route) snippet:
router.get('/',function(req, res) {
Bikes.find(function(err, bikes) {
if (err) {
console.log(err);
} else {
res.json(bikes);
}
}); });
Thanks!
maybe the cause is that you are not using the right port when using /bikes? One solution is to create a small module like this:
// client.js
var axios = require('axios');
var axiosInstance = axios.create({
baseURL: 'http://localhost:4000',
/* other custom settings */
});
module.exports = axiosInstance;
and then use this new module in your code instead of requiring axios
directly:
var client = require('./client');
client.get('relative/path')

Connect to mySql on VPS server eventhough works locally

I have a React front-end, with a Node back-end to connect to mySql for data. It works exactly how I want locally. However, now that I'm moving it to a VPS server, I can't seem to get my configuration correct.
The error I get is: create:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. It's actually returning HTML, of the page that says it's can't find the page.
I setup an express server with this code:(I do realize I need to move login details to an ENV file... just haven't yet)
const express = require('express');
const mysql = require('mysql2');
const connection = mysql.createPool({
host : 'localhost:3306',
user : 'root',
password : 'xxxxx',
database : 'ppr'
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.get('/api/clients/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'clients' table).
connection.query("SELECT * FROM clients", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
console.log(results);
res.json(results);
});
});
});
// Starting our server.
app.listen(3001, () => {
console.log('Listening on port http://localhost:3001');
});
I start this running on the server, and it runs. No errors.
But then my React app makes the first api call, and I get the error because it returns HTML instead of the data I'm expecting. Do I need to do something different to make it work in production? I have proxy setup in my local machine which probably makes it work... but what do I change for production?
Here's the API call that works locally, but not on the server if it helps:
componentDidMount() {
fetch('/api/clients/all')
.then(res => res.json())
.then((result) => {
this.setState({ clients: result });
console.log(result);
})
.then(
fetch(`/api/policy/all`)
.then(res => res.json())
.then((result) => {
this.setState({ policies: result });
console.log(result);
})
);
}

Categories

Resources