How to use ajax from react to express? - ajax

I am a newer about express with react.Now I have to solve one problem.
Until now I make the server side part by express and client side by react including react router and redux, redux-thunk.When I send the post by axios to the express server then there will be error such below
POST http://localhost:8080/api/users 404 (Not Found)
How can I accept CRUD request by redux-thunk in express?
The server side code is below
//app.js
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
app.use('/api/users', userRouter);
app.use('/profile', profileRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
//react redux-thunk side is
axios.post('/api/users', { name: 'LNI' });

You don't have to provide /public instead of just use public.
Path generation is manage by the path module itself.
app.use(express.static(path.join(__dirname, 'public')));
Express POST request is handle like this
app.post('/api/users', userRouter);
Read more about routing from official express documentation - https://expressjs.com/en/guide/routing.html

Related

Need help getting NextJS to acknowledge my rewrites configuration

To eliminate cors OPTIONS requests I want to proxy API calls through the Next.JS server. I've added this configuration change to my next.config.js file:
const withImages = require("next-images");
const { environment } = require("./environments/environment");
module.exports = withImages({
rewrites: async () => [
{ source: "/proxy/api/:match*", destination: `${environment.apiUrl}/:match*` },
],
});
I'm running next version 10.2.3 (latest at time of posting).
Calls to the back-end are performed through fetch within React components. In the browser dev tools I can see that the HTTP request is being performed. A request is sent out to "http://localhost:4200/proxy/api/user/me". It hits the Next server. But after that the Next server does not hit the API server. It responds immediately with a 404. It seems that it hasn't recognized the "rewrites" configuration at all.
This was an issue with an outdated version of nx

How to properly connect Nuxt.js with a laravel backend?

I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt

"Not allowed to request resource" in Safari and "Blocked loading mixed active content" in Firefox. Perfect functionality in Chrome

I am working on an app using a React frontend and Express backend, with GraphQL setup through Apollo (I am following and modifying tutorial https://www.youtube.com/playlist?list=PLN3n1USn4xlkdRlq3VZ1sT6SGW0-yajjL)
I am currently attempting deployment, and am doing so with Heroku. Everything functions perfectly on my local machine before deployment and on Heroku in Google Chrome. However, I get the aforementioned errors in Safari and Firefox, respectively. Wondering why this is happening in these browsers and how to fix.
I have spent about 10 hrs doing research on this. Things I tried that made no difference:
I tried adding CORS to my express backend
I tried serving the graphql endpoint as HTTPS
Moving app.use(express.static) in main app.js server file
I couldn't find many other things to try. Everywhere I looked seemed to say that CORS fixed the problem, but mine persists.
Github link: https://github.com/LucaProvencal/thedrumroom
Live Heroku App: https://powerful-shore-83650.herokuapp.com/
App.js (express backend):
const cors = require('cors')
// const fs = require('fs')
// const https = require('https')
// const http = require('http')
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(cors('*')); //NEXT TRY app.use(cors('/login')) etc...
app.use(cors('/*'));
app.use(cors('/'));
app.use(cors('/register'));
app.use(cors('/login'));
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
server.applyMiddleware({ app }); // app is from the existing express app. allows apollo server to run on same listen command as app
const portVar = (process.env.PORT || 3001) // portVar cuz idk if it will screw with down low here im tired of dis
models.sequelize.sync(/*{ force: true }*/).then(() => { // syncs sequelize models to postgres, then since async call starts the server after
app.listen({ port: portVar }, () =>
console.log(`🚀 ApolloServer ready at http://localhost:3001${server.graphqlPath}`)
)
app.on('error', onError);
app.on('listening', onListening);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Full file is on Github, I tried to post only relevant parts above.
The expected result is that it works in all browsers. It seems from my research that since Heroku serves on HTTPS, Safari and Firefox do not allow requests to HTTP (which is where the graphql server is located, http://localhost:3001/graphql'). When I tried serving Apollo on HTTPS, Heroku just crashed, giving me H13 and 503 errors.
Thanks for any help...
This may also happen during local development when running the front end using HTTPS, but the back end using HTTP.
This is because CORS treats two URLs as having the same origin "only when the scheme, host, and port all match". Matching scheme means matching protocols e.g. both http, or both https.
One solution for local development is to proxy the back end using a tool such as ngrok.
Suppose the front end uses an environment variable which indicates the back end's URL:
BACK_END_API_URL=http://localhost:3005. Then do the following.
Install ngrok
Identify what port the back end is running on e.g. 3005
Run ngrok http 3005 at the command line, which will establish both http and https endpoints. Both will ultimately proxy the requests to the same back end endpoint: http://localhost:3005
After running ngrok it will display the http and https endpoints you can use. Put the one that matches the front end protocol you're using (e.g. https) into your front end environment variable that indicates the back end's URL e.g.
BACK_END_API_URL=https://1234asdf5678ghjk.ngrok.io
Was going to delete this because it is such a silly problem but maybe it will help someone in the future:
I simply replaced all of my 'http://localhost:PORT' endpoints in development with '/graphql'. I assumed that localhost meant local the machine running the code. But an app running on Heroku does not point to localhost. The express server is served on the url (https://powerful-shore-83650.herokuapp.com/) in our case...
At any rate I am so glad I came to a solution. I have a full stack app deployed and connected to a db. Hopefully this post can save someone lots of time.

Getting CORS blocked even after ("Access-Control-Allow-Origin", "*")

I am getting CORS blocked regardless of what I allow. It only yells at me for my POST route, my GET routes it allows just fine. I consistently get
Access to XMLHttpRequest at 'https://simple-startup-survey-backend.herokuapp.com/client_answers' from origin 'http://simple-startup-survey.surge.sh' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using an AJAX to communicate with an EXPRESS server. I allow all requests with the wildcard operator. I have tried sending {crossDomain: true} with my request.
//This is my backend in app.js
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PATCH,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// This is my front end AXIOS call POST request. This is what is //triggering the CORS block
storedData = storedData.concat(storedData2)
axios.post('https://simple-startup-survey-backend.herokuapp.com/client_answers', {crossDomain:true}, storedData,)
.then(function(response){
console.log(response.data , ' save success')
localStorage.setItem("storedData", JSON.stringify(storedData))
window.location.href = "../AnalysisPage/analysis.html";
}).catch()
})
// This is my perfectly functional GET request. It does a bunch of //stuff after this in the .then, but I don't think that is relevant to //this issue
function getgeneralQuestions(){
axios.get('https://simple-startup-survey-backend.herokuapp.com/questions/balanceSheet')
.then(function (response) {
Every damn Google search result on the planet says that what I have in regards to my back end should work. I am using vanilla JS, no JQUERY.
Any help greatly appreciated!
back end Github: https://github.com/TuckerNemcek/SimpleSurveyBackend
front end Github: https://github.com/TuckerNemcek/SimpleStartupSurveyProject
I am running into a similar issue.
My hunch is that surge.sh does not have cors enabled on its server.
My website is actually making the request correctly.
Afterward there is an error and the data is not shown.
Edit: Solved - - - -
Actually, just solved this for myself!
This is my script for publishing.
yarn build; cp build/index.html build/200.html; echo '*' > build/CORS; surge build appname.surge.sh
here is an article about enabling cors for surge.sh https://github.com/surge-sh/example-cors
Also when making changes make sure you are in a new incognito tab each time or go to the network tab on dev tools and Disable cache otherwise your app might be lying to you and thing cors is not enabled when it in fact is enabled.

How to allow Access-Control-Allow-Origin using reactjs and webpack?

I'm runing reactjs in a localhosted server using webpack. I need to make an ajax call from my reactjs application (client side) to my backend, which is also a local hosted server but using a different port. When i make a request to my backend from postman, there is no problem. But when i try to do the same from my react js application, i got this error in my console :
XMLHttpRequest cannot load http://localhost:8888/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Uncaught (in promise) Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
It's seems to be a C.O.R.S issue. After several hours of research on internet i can't find a solution.
There is my code
react :
handleClick(){
console.log('focused')
axios.get('http://localhost:8888/api').then(function(result){
console.log(result)
})
}
webpack config
devServer: {
contentBase: 'http://localhost',
port: 8888,
// Send API requests on localhost to API server get around CORS.
proxy: {
'/api': {
target: {
host: "localhost",
protocol: 'http:',
port: 3000
}
}
}
}
Thanks for helping
Try making your call without the host like this:
handleClick(){
console.log('focused')
axios.get('/api').then(function(result){
console.log(result)
})
}

Resources