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')
Related
So i have a vue project where i have a js file that requests data from an API and that goes fine. I set up a proxy in my vue.config.js file so that every request starting with /api will be redirected to the baseurl of the API, like this:
const { defineConfig } = require('#vue/cli-service');
const path = require('path');
module.exports = defineConfig({
transpileDependencies: true
})
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://dev.liveflow.nl'
},
}
}
}
This works fine for when im in my websites base url and do an axios.get request like axios.get(api/batches/). But when im in my websites 'batches' route, and i do axios.get(api/batches/:id/, the proxy doesnt work. Instead of requesting to (target from the vue.config.js file above) target/api/batches/:id, its requesting to my own websites url/batches/api/batches/:id. So the problem is, that because im in the /batches route, it will leave the /batches in the url, so the proxy i configured doesnt work (i think)
So the code i use in my js file to do all http requests looks like this:
import axios from "axios";
const url = "api/batches/";
class BatchService {
// Get Batches
static async getBatches() {
try {
const res = await axios.get(url);
const data = res.data;
return data;
} catch(err) {
return err;
}
}
// Get Batch by ID
static async getBatchById(id) {
try {
const res = await axios.get(`${url}${id}`);
const data = res.data;
return data;
} catch(err) {
return err;
}
}
export default BatchService;
Because of the proxy, i only have to do "api/batches/" as url, because the proxy recognizes the /api and redirects it to the target.
These to methods work fine when im in my websites baseurl, but when im in a different route, like baseurl/batches, the requests does baseurl/batches/api/batches/:id, while i want it to be target/api/batches/:id.
The error i get is simple: GET http://localhost:8080/batches/api/batches/63722a8ab1194203d268b220 404 (Not Found). It is just requesting the wrong url and using the websites baseurl instead of the target baseurl.
BTW: I need to do the proxy setup. When i just do const url = "target/api/batches/" the API server will deny my request
My english is not that good so i hope im clear enough.
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.
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.
I am creating an endpoint that serves a file generated dynamically. I have written a controller which generates the file after certain operation based on request param fileId.
I am throwing some errors if anything goes wrong while file generation or it is an invalid request. I have used Promise.reject() for throwing error and on successful file generation returning the response {fileName, filePath} as Promise from the controller.
import express from 'express'
import downloadFile from '../controller/file.controller'
const router = express.Router()
router.post('/file/download/:fileId', (req, res) => {
downloadFile(req.fileId).then((fileResp) => {
res.download(fileResp.filePath, fileResp.fileName, function (error) {
if (error) {
console.log('Downloading error')
} else {
console.log('Downloading success')
}
})
}).catch((error) => {
res.status(error.status).json({message: error.message})
})
})
I have observed that file is being served on requesting endpoint but it will be empty of size zero bytes.
I have tried the same thing without Promise which works well. In this approach, I have changed my errors from Promise.reject() to throw error and response from Promise to an object
import express from 'express'
import downloadFile from '../controller/file.controller'
const router = express.Router()
router.post('/file/download/:fileId', (req, res) => {
const fileResp = downloadFile(req.fileId)
res.download(fileResp.filePath, fileResp.fileName, function (error) {
if (error) {
console.log('Downloading error')
} else {
console.log('Downloading success')
}
})
})
I am unable to find the issue in the 1st approach. Is it Promise which is causing the issue or I am doing something wrong?
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) {
});