Axios.get not requesting anything - javascript

I'm trying to use axios to receive data from my backend to my front end so that my webpage can display the data but my axios does not even seem to even run the axios.get code.
const baseUrl = "http://localhost:8081"
axios.get(`${baseUrl}/travels`)
.then((response) => {
const listing = response.data;
console.log(response.data)
})
That's my front end. There was no console.log or anything
app.get('/travels', function (req, res) {
listings.getListings(function (err, result) {
if (err) {
res.status = 500;
res.send(null);
} else {
res.status(200);
res.send(result);
}
});
});
Here's my backend

Possibly it is a cors problem within your webserver since you are accessing a URL from a completely different project.
Install the following:
> npm install cors -S
Then in your express code put this:
...
const cors = require('cors');
app.use(cors())
...
With this you are allowing your webserver to serve the resources to any project outside of itself.
Note: put this code in your backend.

Related

trying to get a node.js project to connect to a javascript project

I'm trying to get node.js to send information back to a website I'm trying to get information from here (rn its a temp a value) but how would I get the information using javascript? or do I need to change something in the node.js project
const app = require('express')();
app.get('/', (req, res) =>
{
console.log("tried")
res.send({"body":"important info"});
//the info passed on can't be a number
}
);
app.listen(3000);
when I tried
fetch("https://discbottest-2.mathman05.repl.co")
.then(r => r.json())
.then(console.log)
.catch(console.error);
it would error: "TypeError: Failed to fetch"
You're probably having issues with CORS. In express it is easy to disable for development using the cors npm module. After you install it using npm install cors something like this should help you solve the problem
const app = require('express')();
app.use(require("cors")());
app.get('/', (req, res) => {
console.log("tried")
res.send({ "body": "important info" });
//the info passed on can't be a number
});
app.listen(3000);
You need to put the port on the fetch call, so it will be:
fetch("https://discbottest-2.mathman05.repl.co:3000/")
.then(r => r.json())
.then(console.log)
.catch(console.error);

How to Set up Vue CORS for different domain API?

I' trying to deploy an Vue app which has a separate backend and which will be hosted in different domain. For example:
meow.cat.xyz (App)
api.meow.cat.xyz (API)
Now after npm run build I tried to preview it locally by running serve -s dist and the application is severing at localhost:5000. However the problem is it not sending API request at the current end point (which is localhost:8000 at local and api.meow.cat.xyz at server). I tried config CORS as following
vue.config.js
module.exports = {
devServer: {
port: process.env.VUE_APP_DEV_PORT,
proxy: process.env.VUE_APP_API_ROOT_PATH,
},
};
.env.development
VUE_APP_API_ROOT_PATH = 'http://localhost:8000/api'
VUE_APP_DEV_PORT = 3000
Note that I'm using axiox. Here is my axios setup.
API.js
import axios from "axios";
const injectAccessToken = (config) => {
const accessToken = localStorage.getItem("access_token");
if (accessToken)
config.headers.common["Authorization"] = `Bearer ${accessToken}`;
return config;
};
const config = {
baseURL: process.env.VUE_APP_API_ROOT_PATH,
};
const API = axios.create(config);
API.interceptors.request.use(injectAccessToken);
export default API;
and Using it as following
Login.vue
import API from "#/api/Api";
<script>
const res= await API.post('login')
</script>
This solution is not working yet. Its sending request at http://localhost:5000. What's the point ? Note that I'm using axios. thanks in advance.
Allow CORS requests from the server
With the Access-Control-Allow-Origin header, you can specify what origins can use your API.
app.get('/api', (req, res) => {
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
res.send({
api: "your request."
});
})
Allow CORS from the app's origin on the server (api).
This has nothing to do with with the client (app)

How to get js file array to node js server?

I have one Javascript file linked to HTML and that js file is calculating an array on clicking submit button in Html and I want to get that data to node js file on post route without displaying it in HTML page. How should I do that?
Your nodeJS program is running on a server, which could just be your computer if you are using localhost, which means that it is in not connected to your HTML page. Therefore, you need to send the data from your js file via fetch request. In your nodeJS file, you need a route for receiving that data, which you create using express.
const express = require("express");
const {json} = require("body-parser");
const app = express();
app.post("/submitData", (req, res) => {
const data = req.body;
console.log(data);
res.status(200).json({"Message": "Data posted", data});
})
app.listen(3000,() => {
console.log("Server running on port 3000");
})
Now, in your javascript file, you need a fetch request.
fetch(http://localhost:3000/submitData, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => {
return response.json();
}).then(data => {
console.log(data)
})
This should do the trick. I would also suggest you download Postman, which is great for testing APIs and trying out http requests
I forgot to point out, after doing:
const app = express();
you should put:
app.use(json());
I apologise for the mistake, it should remove the error you mentioned in the comment.

Express serve javascipt files if authorised

In my client side javascript, I request private content if the user is authorised (using firebase auth) as per below:
firebase.auth().onAuthStateChanged(user => {
if (!user) {
ui.start("#firebaseui-auth-container", uiConfig);
}
if (user) {
import("/private.js").then(module => {
console.log(module.default);
});
}
});
All users are served index.html from the public firebase hosting URL, but only when a user has been authorised do they request the private content. My firebase.json redirects to handle this:
"rewrites": [
{
"source": "**",
"function": "app"
}
]
I am struggling to set up a firebase functions based express backend to serve the javascript. (I haven't added auth checking yet because I want to get it working simply serving the js first).
My firebase function looks like this:
const fs = require("fs");
const functions = require("firebase-functions");
const express = require("express");
const app = express();
app.get("/private.js", (req, res) => {
fs.readFile("private.js", "utf8", function (err, data) {
if (err) throw err;
res.send(data)
});
});
exports.app = functions.https.onRequest(app);
However, when a user gets authorised and the client tries to dynamically import private.js I get the following error: Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. How do I properly set the MIME type to serve js files?
You need to tell the browser that an error occurred, so that it does not try to parse the response as JavaScript. You can do that by sending a status code starting with 4 (client error) or 5 (server error). Here is an example:
app.get("/private.js", (req, res) => {
fs.readFile("private.js", "utf8", function (err, data) {
if (err) {
res.status(403).send('Could not load the data.');
} else {
res.send(data);
}
});
});
I worked it out. I need to use:
res.setHeader("Content-Type", "text/javascript"); //Solution!
res.writeHead(200);
res.end(data);
And it works fine.
Try this
res.type('.js');
res.send(data);

Using NodeJs with React

what is the correct way to use NodeJs with React?
Currently what I am doing is running Node on port 3000 and React on port 3001
Now, I my Node I have this route
app.get("/", (req, res) => {
console.log(req.user)
res.json(req.user)
})
Here console.log shows user details when I manually go to localhost:3000 but If I make an axios request from my react to the above given url it shows undefined.
componentWillMount() {
axios.get("http://localhost:3000/").then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
Now, The req.user is something which were getting from passport google Stratergy and I since the log from localhost:3000 shows the data and the log from localhost:3001 does not show data.
I am confused if I am using the node correct way? i.e sending in request via axios and getting data via res.json
Also, since most of the tutorial or the tutorial I followed used EJS instead of React where user mostly did res.render
I just wanted to know the equivalence of res.render for react in NodeJS
[Update:] I am enabling cross origin resource sharing via plugin in google chrome
EDIT: In discussion with OP I found out that this is most likely a passport authentication middleware related issue. Original answer follows.
Looks like a CORS issue, as your frontend providing server is on port 3001, and backend on 3000. I can show you the way I'm using it (in react+node CORS setup, although the issue has nothing to do with React) and I have no CORS issues:
On frontend I use native browser's fetch:
const fetchRelative = async (path, options) => {
const url = new URL('http://localhost:3000/' + path);
return await ((await fetch(url, options)).json());
};
Here async/await syntax is used. I'm using babel for transpile, but maybe browsers support that natively.
Options provided to fetch are for example:
{
method: 'POST',
body: JSON.stringify(order),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
For a simple get request you can leave the options parameter empty.
On backend (node+koa server) I use this:
const Koa = require('koa');
const koaBody = require('koa-body');
const cors = require('koa-cors');
const startServer = (port) => {
const server = new Koa();
server.use(cors({ origin: '*', allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'] }));
server.use(koaBody());
server.use(bindRoutes());
server.listen(port);
};
Basically the same is for express server (https://expressjs.com/en/resources/middleware/cors.html).
bindRoutes is just koa-router configuration extracted in a separate file:
const Router = require('koa-router');
const bindRoutes = () => {
const router = new Router();
router.get('restaurants', async (ctx) => {
ctx.body = 'abc;
});
return router.routes();
};
CORS plugin is not used here.
P.S.
async/await explaination and Browser support status
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
fetch explaination and Browser support status
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
You can run both your Node server and React app on different ports and proxy the React app back to your Node server. This can be done without a CORS plugin. More details on how to set this up is here: https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0

Categories

Resources