I can get response with postman but cannot get with axios - javascript

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.

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

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

Node.js - Serving file for download using express

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 getting error when I fetch Data from my backend?

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.

How to test Node redirection with Jest

I am using Jest to test my Node REST API.
The problem I have currently is that when I try testing my POST routes, I always receive a status code of 302 due to res.redirect("/").
Example of my POST route:
app.post("/login", async (req, res) => {
try {
let username = 'example'
...
return res.redirect("/");
} catch (error) {
return res.redirect("/");
}
});
jest test file:
'use strict';
const request = require('supertest');
const app = require('./index');
...
describe('Test', () => {
test('POST /login', () => {
return request(app)
.post('/login')
.set('username','example')
.expect(?)
});
});
How can I test that the page has redirected successfully?
As per the Express docs, you can specify a response code as such:
res.redirect(301, 'http://example.com')
The docs state "If not specified, status defaults to “302 “Found”."
Edit: HTTP codes 301 and 302 indicate successful redirection; 301 is permanent and 302 is temporary. Both are "successful" as far as a computer is concerned.
I assert the response.headers.location for redirection location. This way I can write test cases by mocking a single class function that causes different redirections.
test('Should handle "/redirectUri"', async () => {
const exchangeForAuthTokenSpy = jest.spyOn(
OAuth.prototype,
'exchangeForAuthToken',
)
exchangeForAuthTokenSpy.mockResolvedValue({
success: true,
access_token: 'access_token',
})
const app = server('', AuthRoutes)
const res = await request(app).get('/redirectUri?code=code&state=state')
expect(exchangeForAuthTokenSpy).toHaveBeenCalledTimes(1)
expect(exchangeForAuthTokenSpy).toHaveBeenCalledWith('code', 'state')
expect(res.status).toEqual(301)
expect(res.headers.location).toContain(
'/callback?code=200&token=access_token',
)
})
It is late, but could help someone. You can test like below
it('redirection test', function (redirect) {
request(app)
.get('/url')
.expect(302, redirect)
});

Categories

Resources