I have a redux action which fires whenever a user on a site tries to change their profile. It does this through an api call middleware that I wrote using a tutorial from Mosh.
export const updateUserProfile =
({ id, name, email, favouriteThing, password, confirmPassword }, headers) =>
(dispatch) => {
dispatch(
apiCallBegan({
url: `api/users/profile`,
data: { id, name, email, favouriteThing, password, confirmPassword },
headers,
method: 'put',
onStart: userUpdateRequested.type,
onSuccess: userUpdateReceived.type,
onError: userUpdateFailed.type,
})
);
};
The app routes are like this:
<Route path='/profile' render={ProfileScreen} exact />
<Route path='/profile/page/:pageNumber' render={ProfileScreen} exact/>
I have pages on the profile page route because I have a React component which displays all the items that the user has created in a table, and I need the table to handle multiple pages. I couldn't figure out how to make a single component within a page change pages without changing the whole page, so I made it that the whole page changes.
The endpoint is this:
router
.route('/profile')
.put(protect, updateUserProfile);
I submit the new data using a submit handler which looks like this:
const submitHandler = (e) => {
e.preventDefault();
if (password !== confirmPassword) {
setMessage('Passwords do not match');
} else {
dispatch(updateUserProfile(data, headers));
}
};
This all works fine when I am at this URL: http://localhost:3000/profile
When I go to page 2 of the profile this is the URL: http://localhost:3000/profile/page/2 and I get the following error:
404 Not Found trying to reach /profile/page/api/users/profile
I logged location.pathname when the submitHandler is triggered and I get '/profile' which appears correct.
However when I log the req.originalURL at the error middleware in express I get /profile/page/api/users/profile
So something is changing the originating URL between when the function is called in the frontend and how it is received in the backend.
Is there anyway to keep req.originalURL at '/profile' irrespective of what page of the profile I am on? I have tried using the Switch component in React Router Dom and setting the location of profile pages route to '/profile' but this breaks the profile pages route and the profile page won't load at all when you click on next page.
I've done a lot of googling and testing in the app and I can't seem to think of anything, which makes me think I have a fundamental misunderstanding of what is going on here. I'd really appreciate some help if someone has any thoughts.
Turns out it was a very simple fix that someone pointed out to me on another site. Thought I would share it here.
There needs to be a forward slash at the beginning of the url in the request, otherwise it is interpreted as a relative path.
url: `/api/users/profile`
Related
If I manually go to this url: https://localhost:1234/signout-oidc
Then it signs out of my azure AD connected mvc application.
However going to this url just presents me with a blank white screen. I'm trying to do this on a 'log out' button on my MVC site, so ideally I would have it redirect. I might also want to do some custom logic so it would be good if I could put this into an action.
I've seen some suggestions like this:
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
However nothing happens when running these lines, I remain signed in.
Can anyone tell me what the correct way is to sign out the way that URL does within my application?
In the controller, simply put:
return SignOut("Cookies", "OpenIdConnect");
To control the URL, in the program.cs or startup.cs, put a handler in:
builder.Services.AddAuthentication(authOptions =>
{
authOptions.DefaultScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.Events.OnSignedOutCallbackRedirect += context =>
{
context.Response.Redirect("/"); // Redirect URL
context.HandleResponse();
return System.Threading.Tasks.Task.CompletedTask;
};
});
I am having this problem that whenever i try to visit the page localhost:3000/blog/test directly it returns a 404 error. But whenever i try to visit it using <Link> component it works fine.
This is my code <Link href={{ pathname: '/blog', query: {slug: 'test'} }} as="/blog/test"><a className="nav__link">Blog</a></Link>
and i have a file blog.js in my pages folder.
What's happening is that on the client, with the Link component, you are creating a link to the blog.js page by setting "/blog" as the pathname.
When you go directly to the URL/blog/test, Next.js will try to render the page on the server and to do so will look for the file /pages/blog/test.js. That file doesn't exist, and Next.js doesn't know that you want to load the blog.js page and set query.slug to to the second part of the URL.
To do this, you need to map that route on the server to load the page you want, and pull the params you want out of the URL.
The Next.js docs cover this in Server Side Support for Clean URLs by using express to setup a custom server.
You can view the full code to get it working there, but your custom route will look something like this:
server.get('/blog/:slug', (req, res) => {
const actualPage = '/blog'
const queryParams = { slug: req.params.slug }
app.render(req, res, actualPage, queryParams)
})
You'll have to use now.json to set up your routes. Also it is important to note that it's now that builds the route so visiting it on the client side wont work if you are using localhost. Build your project with now and it should work.
Also the "as" parameter would be as={{ pathname:/user/manage/${variable}}}
I have a simple web-app made with create-react-app and express.
All of the pages made with react router work fine locally, as well as online on my own machine once deployed to Heroku.
But, after testing online on other machines, I can't access these pages - whenever I click the links to them it displays Cannot GET /*route*
I still have the *name*.herokuapp.com domain if that affects it in any way
The redirect code I use is as follows: (I use firebase and react-bootstrap as well)
class App extends Component {
render() {
return (
<div>
<MyNavbar/>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/eateries" component={Eateries}/>
<Route exact path="/thank-you" component={ThankYou}/>
</Switch>
</div>
);
}
Redirecting to /thank-you:
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.location = "thank-you"
}
})
}
So essentially when a user signs in through a modal component it should take them to /thank-you
Redirecting to /eateries:
<NavItem href="/eateries">
For Eateries
</NavItem>
Is there something wrong with the way I'm redirecting users or using react router in general?
It's hard to know without seeing your server code - but in order to support react-router's rendering mechanism, you need to use a wild card route in your server code:
app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html'));
This basically means "for any route not already matched, send the index.html file", which will then load your webapp, which in turn will handle routing. Note that you need to add the static middleware serving your assets before this - that's a gotcha I've forgotten many times. Most of your server file would then look like this:
const express = require('express');
const app = express();
app.use(express.static('build'));
app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html'));
app.listen(process.env.PORT, () => console.log('listening for connections'));
Now, this would seem to work either way locally, since your web app is already loaded, and handles routing for you.
However, I've noticed that you're using window.location when redirecting your user. This makes some browsers at least (probably all) request the new page from the server, instead of letting the app deal with it. Instead, use the provided history property, which contains a push method.
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.props.history.push('/thank-you');
}
});
}
This adds a new entry to the history stack. If you want a regular redirect, you should use .replace instead.
Hope this helps!
I'm using react router v4 and trying to implement a protected api view. E.g., if a user goes to /add/ url while not logged in, they would be redirected to /login/, then upon successful login taken to /add/.
I was able to implement it using the idea from this post. However, I run into issues whenever the initial http request that loads the app is from a protected url.
E.g. when I enter in the browser '/add/' and hit enter, I run into async issues where my app doesn't have time to make an ajax request to the server to check for login, and as a result the router ends up routing to the /login/ because ajax auth request hasn't completed.
Can someone recommend login workflow should be handled generally, taking into account the fact that a user may start their session on a protected url like '/add/' and not on the home '/'?
Found a simple, standard React pattern solution. Just don't render <Route> components unless the log in ajax check has completed.
So when the app loads for the first time, initialize a state checkingLogIn to true and don't render any <Route> component unless it becomes false. When the ajax function checking for log in completes, call setState to set checkingLogIn to false. This will cause the <Route> to render and redirect correctly.
Edited with sample code:
componentDidMount(){
// call the ajax function that checks if the user is logged in and update state when it returns; using fetch API here
fetch(your_url, your_credentials)
.then(
that.setState({checkingLogIn: false, isLoggedIn: true})
)
.catch(...)
}
// render method of the React component
render(){
if(this.state.checkingLogIn){
return (<div>Loading...</div>)
}
else {
return (
<Route path={some_path} render={props => <SomeComponent {...props} />}></Route>
)
}
}
I have several components displayed with react router that have dynamic url paths. An example path I have is
<Route path="/newproject/:id" onEnter={checkSesh} component= {ProjectDetails} />
When entering this component, I have a componentWillMount function that extract the id part of the url so that I can get the info for the correct project and render it on the ProjectDetails component.
componentWillMount() {
var id = this.props.router.params.id
this.props.teamDetails(id);
}
this.props.teamDetails(id) this calls a redux action creator that will make an axios request to an express route that will get the project info from the database.
export function teamDetails(id) {
return function(dispatch) {
axios.get('/getteaminfo/' + id)
.then(res => {
dispatch({ type: "SET_TEAM_DETAILS", payload: {
teamInfo: res.data.teamInfo,
admin: res.data.admin,
adminID: res.data.teamInfo.teamAdmin,
teamMembers: res.data.teamInfo.teamMembers
}
})
});
}
}
everything works fine upon visiting the page after already being logged in etc. But when I refresh the page /newproject/:id, i get an error Uncaught SyntaxError: Unexpected token <. An example url in my browser looks like http://localhost:3000/newproject/58df1ae6aabc4916206fdaae. When I refresh this page, I get that error. The error is complaining about my <!DOCTYPE html> tag at the very top of my index.html for some reason. This index.html is where all of React is being rendered.
When page is refreshed store state is not preserved. Make sure the state is not important to load the page, or at least initialized properly every time.
For e.g. login information if saved in store and not on browser with localStorage or cookies etc.. then on refresh, the error will come when trying to access /getteaminfo/ route through axios. The response will have error html and it can't be parsed by js.
Please check your web console on for more information. You can use chrome extension like https://github.com/zalmoxisus/redux-devtools-extension which will show your store and etc..
Make sure to check what /getteaminfo/ gives with id is not passed.
Also, make sure on your server side, did you route requests to react-router path through something like this?
e.g. express js,
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
be sure to sendFile with the real location of index.html
I found the answer here: react-router dynamic segments crash when accessed I added <base href="/" /> into the <head>of my index.html. You can also read more info here: Unexpected token < error in react router component