'How do you pass URL param /:id from axios to express?
React Beginner Here. I'm building a practice chat app and trying to pass a chat id from the URL to express. I don't know if I'm doing it right but the id gets set using navigate and when they get redirected, a useEffect is supposed to get the /:id and pass it to express using Axios and return the actual chat. However, for example I send something like /messages/chat/1, and pass it to express, all I get is "/:id" and not 1. Code below.
Idea: Maybe I can use the context API to store and pass it. Might try later
Update: I tried with context API. It worked but I think this is not the right way to do it lol
section.jsx - passes chatId to url and redirects
import React, {useState, useEffect, useContext} from 'react'
import AuthContext from '../../../context/AuthProvide'
import styles from './section.module.css'
import {axios} from '../../../context/axios'
import { useLocation, useNavigate } from "react-router-dom"
const ENTER_URI = '/enter_chat'
const Section = (props) => {
const { state } = useLocation();
const navigate = useNavigate();
const { user } = useContext(AuthContext)
const [value, setValue] = useState(props.subjectId)
function handleEnterChat(e) {
e.preventDefault()
axios.post(ENTER_URI, {
user_section: user.user_section_id,
subject_id: value
}).then(res => {
navigate(`/messages/chat/${res.data.chat_id}`)
}).catch(err => {
})
}
return (
<>
<form className={styles.chatItem}>
<button onClick={handleEnterChat} className={styles.enterChat}>{props.subject}</button>
</form>
</>
)
}
export default Section
chat.jsx - useEffects to the backend and get data
import React, {useState, useEffect, useContext} from 'react'
import AuthContext from '../../../context/AuthProvide'
import { axios } from '../../../context/axios'
const GET_CHAT_URI = '/messages/chat/:id'
const _Chat = () => {
const { user } = useContext(AuthContext)
useEffect(() => {
axios.get(GET_CHAT_URI, {}
).then(res => {
alert('worked')
console.log(res.data.chat)
}).catch(err => {
alert('error')
console.log(err)
})
}, [])
return (
<>
_Chat
</>
)
}
export default _Chat
getChat.js - supposed to read the get
const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const cors = require('cors')
const mysql = require('mysql')
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
})
router.use(cors({
origin: ['http://localhost:3000', 'http://localhost:9000', 'http://localhost:3001'],
credentials: true,
}))
router.use(express.urlencoded({extended: true}))
router.use(express.json())
router.get('/:id', (req, res) => {
const chatId = req.params.id
console.log(chatId);
res.json({message: "Hello World"})
})
module.exports = router
server.js
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const cors = require('cors')
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:9000', 'http://localhost:3001'],
credentials: true,
}))
app.use(express.json())
app.use(express.urlencoded({extended: true}))
...
const getChat = require('./routes/chat/getChat')
...
app.use('/messages/chat/', getChat)
const PORT = process.env.PORT || 9000
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`)
})
routing.jsx - may ve important
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Messages from "../pages/messages/messages";
import Chat from "../pages/messages/chat/chat";
...
import ProtectedRoute from "../pages/Protected_Routes/protected";
const Routing = () => {
return (
<>
<Router>
<Routes>
...
<Route
exact
path="/messages/chat/:id"
element={
<ProtectedRoute>
<Chat />
</ProtectedRoute>
}
/>
</Routes>
</Router>
</>
);
};
export default Routing;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
