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)
})
}
Related
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
I have been using SpringBoot for web development before, which needs to manage session, database, HTML and other functions.
Recently, I am going to use VUE, replacing the HTML part of SpringBoot.
Now I use the following two methods for development, but I am troubled by problems such as cross domain and session cannot be keeped.
Use nodejs as the enter of the website and use vue.config to configure the agent. In this way, the URL located is correct, but the login status cannot be saved.For example, if submit a form for login, the background returns to the successful message for login, but if refresh the page, it will show 'not login'. The 'devServer' configuration is as follows
devServer: {
open: false,
host: 'localhost',
port: 8080,
proxy: {
'/ API: {
Target: 'http://192.168.9.211/',
ChangeOrigin: true,
ws: true,
PathRewrite: {
'^ / API' : ' '
},
cookieDomainRewrite: 'localhost',
}
}
}
Use Nginx as gateway, and then forward the HTML request to NodeJS, and the data request (such as JSON data) to SpringBoot.I haven't had time to experiment with this idea, because it may still occur session saving issues.Nginx is forwarding HTTP requests to Nodejs and SpringBoot, so this saved session is from Nodejs or SpringBoot?
So ask if anyone has done a similar project and if you can share your experience.
I've built an SPA with Laravel, Vue js, Vuex and Laravel Passport for authentication.
I have a vuex store file that contains the apiURL and serverPath that I use throughout my application via services, where I make my axios requests.
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
import * as auth from './services/auth_service.js';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
apiURL: 'http://highrjobsadminlte.test/api',
serverPath: 'http://highrjobsadminlte.test',
profile: {},
},
mutations: {
authenticate(state, payload) {
state.isLoggedIn = auth.isLoggedIn();
if (state.isLoggedIn) {
state.profile = payload;
} else {
state.profile = {};
}
}
},
actions: {
authenticate(context, payload) {
context.commit('authenticate', payload)
}
}
});
As you can see in the apiURL and serverPath variables, I'm developing on my localhost using this domain: http://highrjobsadminlte.test
After deploying my application to GoDaddy, I changed these variables to my actual domain: https://highrjobs.com
Now I'm getting this error:
app.js:26402 Mixed Content: The page at 'https://highrjobs.com/candidate/search' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://highrjobsadminlte.test/api/candidate/search'. This request has been blocked; the content must be served over HTTPS.
When I click on the app.js file, I can see that it still has the store.js code with the local domain in the apiURL and serverPath variables, But they are changed in the files on the Server 1000%.
I thought it's a caching issue so I ran these commands:
php artisan route:cache
php artisan cache:clear
php artisan config:cache
and it doesn't fix the issue. How can I fix this?
Mixed content: This request has been blocked
this error mostly get because
you are using https://highrjobs.com domain which is https protocol and u are using some url inside your application which is not https
apiURL: 'http://highrjobsadminlte.test/api',
serverPath: 'http://highrjobsadminlte.test',
like this u need to move in to https
in this error
app.js:26402 Mixed Content: The page at 'https://highrjobs.com/candidate/search' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://highrjobsadminlte.test/api/candidate/search'. This request has been blocked; the content must be served over HTTPS.
you can clearly see server try to serve https://highrjobs.com/candidate/search this secure url this unsecured api http://highrjobsadminlte.test/api/candidate/search
so fix this u need to use https to your api url as well
hope i explained well
and your code should be
apiURL: 'http://highrjobsadminlte.test/api' to apiURL: 'https://highrjobs.com/api',
Thank you
Sorry, I forgot to run npm run production before deploying. So my app.js file still had the old URL's.
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.
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