简体   繁体   中英

Send URL params from React to Node JS API

I'm creating a website using MERN and I am struggling to pass the username in my URL to React.

I want to get every blog posts from one user that I pass in the URL. For this, I use find() in my server.js . This works on my NodeJS server http://localhost:3333/

app.get('/blog/:username', (request, reponse) => {

mongo.connect(url, function (err, db) {
    var dbo = db.db("mern-pool");
    var cherche_user = request.params.username; 
    dbo.collection("posts").find({username: cherche_user}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        var students = result;
        reponse.send(result);
        db.close();
        });
    });
});

I need to pass that data into my React blog-indiv component. However this doesn't work, my console.log(this.state) render an empty Array.

It does work when I change axios.get('http://localhost:3333/blog/:username') to axios.get('http://localhost:3333/blog/user123')

    export default class BlogIndiv extends Component {

    constructor() {
        super();
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        axios.get('http://localhost:3333/blog/:username')
            .then(response => {
                this.setState({ posts: response.data });
                console.log(this.state);
            })
    }

    render() {
        return(
            <div>
                <h1>HE</h1>
                {this.state.posts.map(e  => {
                        return (
                            <Sub title={e.title} 
                                content={e.content}
                                author={e.username}
                            />
                        )}
                    )}
            </div>
        ) 
    }
}

You can pass it like this using backticks.

let anyvar = user123
axios.get(`http://localhost:3333/blog/${anyvar}`)

Hope this answers your question! Happy coding!

Yo can try changing your axios url to the following:

axios.get('http://localhost:3333/blog/'+id)

after receving the id in the function like this:

componentDidMount(id)

Change axios.get('http://localhost:3333/blog/:username') to

const username = "something"
axios.get(`http://localhost:3333/blog/${username}`)

you can install npm i @eneto/axios-es6-class

then create UserApi.ts or UserApi.js

import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Api } from '@eneto/axios-es6-class';
import { Credentials, Token, User } from './interfaces';
import { axiosConfig, API_BASE_URL } from "./axios-config";

class UserApi extends Api {
    public constructor (config?: AxiosRequestConfig) {
        super(config);


        // this middleware is been called right before the http request is made.
        this.interceptors.request.use((param: AxiosRequestConfig) =>
            ...param,
            baseUrl: API_BASE_URL
        }));

        // this middleware is been called right before the response is get it by the method that triggers the request
        this.interceptors.response.use((param: AxiosResponse) => ({
            ...param
        }));

        this.userLogin = this.userLogin.bind(this);
        this.userRegister = this.userRegister.bind(this);
        this.getAllUsers = this.getAllUsers.bind(this);
        this.getById = this.getById.bind(this);
        this.getBlogsByUiserId = this.getBlogsByUiserId.bind(this);
    }

    public getBlogsByUiserId (id: number): Promise<Blogs[]> {
        return this.get<Blogs[], AxiosResponse<Blogs[]>>(`/blog/${id}`)
           .then((response: AxiosResponse<Blogs[]>) => response.data);
    }

    public userLogin (credentials: Credentials): Promise<Token> {
        return this.post<string,Credentials, AxiosResponse<string>>("domain/login", credentials)
            .then(this.success);
    }

    public userRegister (user: User): Promise<number> {
        return this.post<number, User, AxiosResponse<number>>("domain/register", user)
            .then(this.success)
            .catch((error: AxiosError<Error>) => {
                throw error;
            });
    }

    public async getAllUsers (): Promise<User[]> {
        try {
            const res: AxiosResponse<User[]> = await this.get<User,AxiosResponse<User[]>>("domain/register");

            return this.success(res);
        } catch (error) {
            throw error;
        }
    }

    public getById (id: number): Promise<User> {
        return this.get<User,AxiosResponse<User>>(`domain/users/${id}`)
            .then(this.success)
    }
}

export const userApi = new UserApi(axiosConfig);

Then you create your axios-config.ts

import { AxiosRequestConfig } from 'axios';
import * as qs from "qs";

export const API_TIMEOUT = Number(process.env.API_TIMEOUT) || 10000;
export const API_BASE_URL = process.env.API_BASE_URL || "http://localhost:3333";

export const axiosConfig: AxiosRequestConfig = {
    withCredentials: true,
    timeout: API_TIMEOUT,
    baseURL: API_BASE_URL,
    headers: {
        common: {
            "Cache-Control": "no-cache, no-store, must-revalidate",
            Pragma: "no-cache",
            "Content-Type": "application/json",
            Accept: "application/json",
        },
    },
    paramsSerializer: (params: string) => qs.stringify(params, { indices: false }),
};

NOW ON yow Component you can do some like:

import {userApi} from "./UserApi";

 export default class BlogIndiv extends Component {

    constructor() {
        super();
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        const id = 1;
        return userApi.getBlogsByUiserId(id)
         .then(res=> this.setState({ posts: res }))         
   }

    render() {
        return(
            <div>
                <h1>HE</h1>
                {this.state.posts.map(e  => {
                        return (
                            <Sub title={e.title} 
                                content={e.content}
                                author={e.username}
                            />
                        )}
                    )}
            </div>
        ) 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM