Express get url is wrong - javascript

I am sending an axios request to an express url "getstatus" - on my local development everything is fine, but once the files are on a server there is still my localhost in the url path.
this.$axios.get('api/getstatus', {
}).then(function (response) {
})
.catch(function (error) {
});
app.get('/getstatus', async (req, res) => {
// stuff happening
})
-> ok on localhost
-> error on sever: Request URL: http://localhost:3000/api/getstatus
Why is my local development url still getting used? it should be http://myserver.com/api/getstatus

It seems like the axios get request should be /api/getstatus not api/getstatus
Another thing is you should set an API_URL variable in your dot env file and on development set it to localhost and on your server set it to your server URL.
something like this
this.$axios.get(`${process.env.API_URL}/api/getstatus`, {
}).then(function (response) {
// Code here
})
catch(function (error) {
// Error code here
});

Can you try below code change to use the full url in the get request. If it works you can parameterize the myserver.com
this.$axios.get('http://myserver.com/api/getstatus', {
}).then(function (response) {
})
.catch(function (error) {
});

Related

nuxt app deployed to Netlify: fetch to api working locally, but not on deployed site: getting a 404

I have a Nuxt.js app that I'm trying to deploy to Netlify - and everything works on my local machine, but the fetch request to the api returns a 404 when it's deployed to Netlify. I don't know how to make that server route available to my client when it's deployed.
the fetch request in my api-client.js file looks like this:
async fetchInfo(state) {
let response = await fetch(`/api/info/${state}`);
let data = await response.json();
return data;
}
and the api looks like this (in api/index.js file):
const rp = require('request-promise');
const apiKey = process.env.POLICY_API_KEY;
export default function (req, res, next) {
if (req.url.includes("/info")) {
let stateAbbr = req.originalUrl.slice(-2);
rp({
uri: `https://third-party-api-here.com/states/${stateAbbr}/`,
method: 'GET',
headers: {
'token': apiKey,
},
json: true
}).then(function success(response) {
if (response) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
return;
}
}).catch(function error(response) {
console.log('error', response.error);
});
return;
}
next();
}
I think this might have something to do with CORS? I'm getting this error in the browser when I try to hit that route in the deployed app:
GET https://my-app-name.netlify.app/api/info/MN 404
SyntaxError: Unexpected token < in JSON at position 0
As mentioned in the comment above, you need to have a Node.js of some sort.
Hence, hosting on Heroku fixed OP's issue (Netlify is only for static files).

How do I connect service to a Cloud Foundry app?

I'm new to IBM cloud and I'm trying to build an application where I can write a text, press a button and that text is analysed by the service tone analyser returning a JSON so I can show it.
I have created an instance of said service and I have connected it to my application (a toolchain) using the 'connections' tab on the service.
I also have this code on the app.js file on my app:
const ToneAnalyzerV3 = require('ibm-watson/tone-analyzer/v3');
const { IamAuthenticator } = require('ibm-watson/auth');
const toneAnalyzer = new ToneAnalyzerV3({
version: '2019-10-10',
authenticator: new IamAuthenticator({
apikey: [API key found in service credentials],
}),
url: [API url found in service credentials],
});
app.get('/', function(req, res) {
res.render('index');
});
app.post('/api/tone', async function(req, res, next) {
try {
const { result } = await toneAnalyzer.tone(req.body);
res.json(result);
} catch (error) {
next(error);
}
});
The problem is that when I make the following call on my javascript:
$.post( "/api/tone", {text: textInput}, function(data){
console.log(data);
});
I get the error: 500 (Internal Server Error).
Does anybody know what I am doing wrong?
The issue is that you are sending req.body to be analysed for tone. If you take a look at the API Docs - https://cloud.ibm.com/apidocs/tone-analyzer?code=node#tone - you will see that you only need to send
const toneParams = {
toneInput: { 'text': text },
contentType: 'application/json',
};
I doubt very much that req.body has a toneInput field, and if it does have contentType it may not be set to one of the allowable values.

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')

Download a PDF file in Node and redirect into front end React

Can you help me to download a file in Node.js and redirect page into the front end? I am using MERN stack (Mongo, Express, React, Node).
After authenticating with the Google Auth, I want to download a file in Node, then I want to redirect the page.
router.get(
'/auth/google/callback',
passportGoogle.authenticate('google', {
failureRedirect: '/',
}),
(req, res) => {
try {
var file = 'resume.pdf';
res.download(file, (err => {
if (err) {
console.log(err)
} else {
window.location.href = '/';
}
}));
}
);
I tried this code, but after downloading it's not redirecting page to front end.
(req, res) => {
try {
var file = 'resume.pdf';
res.download(file, (error => {
if (!error) {
window.location.replace("http://stackoverflow.com");
} else {
console.log(error)
}
}));
}
catch {
console.log(error)
}
Since the headers are already sent with the download response, you'll have to go different route than this.
You'll need to change the response yourself.
var data = //filedata
res.set({
Content-Type: 'text/plain',
Location: '/'
});
res.end(data);
Utilize the Location header accordingly for your redirect.
On the client, you'll want to use:
window.location.replace("/headerLocation");
You want to use this on the client after the success of your callback to your download pdf method.
The reason your getting window undefined is because you're attempting to execute this on your nodejs server. The window object exists on the client.

In MEAN web app, sending HTTP response error 403, 500 from Express (server side), not captured in errorCallback function in Angular controller

In my Node web app, I'm sending an HTTP GET request in one of the Angular controllers, and in the same route defined in Express, somewhere in the route logic, I'm sending an HTTP 500 response (tried 403 Error as well). In the Angular controller, this error is not captured in the correct callback function, any insights?
myApp/public/javascripts/main_controller.js:
mainApp.controller('myController', function($scope, $routeParams)
{
...
$scope.myFunction = function (profile) {
$http({
url: '/route1/" + username,
method: "POST"
})
.then(function successCallback(response)
{
//ERROR: This is printed after the GET request
console.log("success updating likes");
}, function errorCallback(response)
{
//ERROR: This is NOT printed after the GET request
console.log("error: ", response.error);
});
};
});
myApp/routes/api.js:
router.route('/route1/:username')
.post(function(req, res) {
User.findOne({'user': param1 }, function (err, user)
{
//...Logic to Find and update a property of collection
if (user.property == condition)
{
res.status(500).send({ error: 'some error' });
}
//...Other logic
})
});
Though it should work anyway, but try to return from res.status or else your code will continue to run and it could be getting confused somewhere and sending multiple headers if you have more res below.

Categories

Resources