I am using the boilerplate on https://github.com/react-boilerplate/react-boilerplate . The problem is that when I'm hitting API's It's returning error 404. I'm not able to get from where it is setting up the host (which is always going localhost).
no CORS error is also coming up on browser.
Prior to this I was working on create-react-app, there I simple put a "proxy" property in package.json and everything worked fine.
Today I set up this boilerplate for the first time and I would say it's a lil confusing _:)
You can specify API base url like this:
const API = process.env.NODE_ENV !== 'production' ? 'http://google.com' : 'http://localhost:5000'
So in development it will always point to localhost and in production it will point to other your prod server.
For people still searching,
all you need is to create something like this in server/index.js
app.get('/api/user', (req, res, next) => {
let parsedBody = JSON.parse(req.body)
res.send({ express: 'Hello From Express.' });
});
on client side request to /api/user
axios.get(`/api/user`)
.then(function (response) {
console.log("/api/user response", response);
})
.catch(function (error) {
console.log(error);
});
cheers
Related
//let firstTestURL = "https://blog.naver.com/mayoha/223015532241";
//let testURLonProxy = "naver/siji5000/223015377877";
let testURL = "https://peursen.tistory.com/270";
axios.get(testURL)
.then((response) =>{
let body = response.data;
const $ = cheerio.load(body);
let theURLtitle = $("title").text();
console.log(theURLtitle);
})
.catch(err =>{
console.log(err);
})
I am making web Scraping web program using React.
it have input for URL. if user put in the URL , the program will scraping to title and author.
but I face the problems Because of CORS.
so I searched, I wrote the proxy config for 'firstTestURL'.
but in fact that this program will meet a lot of URL with CORS.
so first, I wrote proxy config for few important URLs.
but this testURL is difficult.
in that case(that web platform) the words before fist dot is blog's name. and next is the blog platform.
I wanted make proxy config for that
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app){
app.use(
createProxyMiddleware('tistory/', {
target: 'tistory.com/',
pathRewrite: {
'tistory/^':''
},
changeOrigin: true
})
)
};
yes it didn't works.
how can I fix the config? or do you know about pass CORS ?
when I used just the test URL , I blocked CORS
And I tried proxy (I know.. it probably something wrong way to use)
when I posted, I only used middleware proxy.
but I find out
outside proxy sever like https://cors-anywhere.herokuapp.com/
yes, it only for dev. but it worked.
so I decided payed proxy server
(because I don't want handle own proxy server)
Currently, I'm trying to get axios data from node.js. and i can get the result on local url , however after i build it and deploy it, the post method get 404 error. so i tried to use get method to test it. it gets react html result .
it's totally okay when i do it on local. but only it doesn't work when i build and deployment.
I assumed it's because proxy problem so i installed http-proxy-middleware library and
I try to set up setupProxy.js on my react folder.
this is the example from
"https://create-react-app.dev/docs/proxying-api-requests-in-development/"
but it still doesn't work.
i want to know what can make this issue.
//node.js
app.get("/test", (req, res) => {
res.send({ hello: "Hello world" });
});
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "dist")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
//react
const getTest = () => {
axios
.get(`${backend}/test`)
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
};
The proxy configuration only applies to the webpack-dev-server you use when developing your React app...
Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.
I would suggest just using the simpler version by adding this to your package.json
"proxy": "http://localhost:5000",
You should also make sure your Express app is configured to handle API requests in both dev and production modes. To do so, I'd recommend using the same routes as used in the requests from the front-end...
app.get("/api/test", (req, res) => {
res.send({ hello: "Hello world" });
});
// or even better
app.use("/api", myApiRouter);
Now your React app can make requests to /api/test in both development and production modes
axios.get("/api/test").then(({ data }) => console.log(data));
In development mode, the proxy configuration will forward the requests to your Express app.
In production mode, your Express app will be serving the built React app via express.static() so they'll be on the same domain.
I have a weird behaviour while integrating a json-server api with axios.
I use json-server to serve a db.json file
json-server --watch db.json --port 4000
and in my react application I use axios to call "http://localhost:4000/tasks"
Testing it on postman, the API returns results and it is working fine.
but using the code snippet below (axios) it concatenates both domains of the react app and the api Url to the request.
try {
return axios({
method: 'GET',
url: `http://localhost:4000/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
I check in the browser network and I the request Url like that
Request URL: http://localhost:3000/http//localhost:4000/tasks
and therefore throws a not found - 404 exception
Any idea why is this happening?
The weird thing is that When I use another API like star wars api "https://swapi.co/api/people/1", It works like a charm.
Thanks in advance...
I've fixed this problem by using environment variables.
I just created a ".env.development" file and added "REACT_APP_API_BASEURL = 'http://localhost:4000'".
And then I used it as follows:
try {
return axios({
method: 'GET',
url: `${process.env.REACT_APP_API_BASEURL}/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
and it worked perfectly.
Just faced this issue, it's because the url used in axios is wrong. In this case, the url in the original question is
http://localhost:3000/http//localhost:4000/tasks
Notice http//localhost:4000/tasks this is missing a colon after http. Fixing the url will fix this issue in case someone else is facing this again
fetch('https://mylocalip:5000/api/token')
.then(function (response) {
console.log('response : ',response)
return response.json();
}).then (function (response) {
this.setState({
token: response.token
});
}).catch(function (error) {
console.log(error);
});
I read in issues on react native and use my ip to call local api. but still get network error. Im on latest version of react-native 0.55.4.
I think the correct uri should be http://mylocalip:5000/api/token (remove https) or https://mylocalip/api/token (remove port)
So I finally figured out that the issue was with the certificate. React native was not able to verify certificate self signed on localhost.
I am newbie in firebase admin SDK and trying to get it work on my angularjs app, using and following the steps here and this here:
I have correctly setup my firebase admin SDK and initialized it like this in server.js file on my node server:
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
app.post('/.firebase-user', function (req, res, nex) {
admin.auth().getUser(req.body.uid)
.then(function (userRecord) {
// See the tables below for the contents of userRecord
console.log("Successfully fetched user data:", userRecord.toJSON());
})
res.status(200).send({data: userRecord.toJSON()});
return nex();
.catch(function (error) {
console.log("Error fetching user data:", error);
res.status(117);
return nex();
});
});
now I want to access userRecord.toJSON() inside my controller:
$http.post('/.firebase-user', {uid: firebase.auth().currentUser.uid})
.then(function(response) {
console.log($scope.data, response.userRecord);
});
But it is not printing the userRecord.toJSON(), instead I get true undefined in the console.
Please help me to fetch the info back inside my app. thanks
It looks like there are a few issues with your (Express) app request handler:
In your Angular code, you make a request to the /.fb endpoint but in your server code you are listener on the /.firebase-user endpoint. I assume you want these to both be the same.
Your server code never actually sends a response to the Angular code. I'm surprised your then() completion handler ever actually completes. You should need to explicitly send a response with something like res.status(200).send(userRecord.toJSON()) in the success case and res.status(400).send({ error: error }) in the error case.
You should add a catch() to your Angular code to ensure you are catching any errors or failed requests being made by the server code.