admin管理员组

文章数量:1392095

I am receiving my data from my POST request. I want to use that data as a variable in a GET request.The data from the POST request is user inputted to make different queries on the 3rd party API> How can I save my data as a variable to do so? You can see my request.body is being saved as const data. And I need it used as ${data} in my get request. I am pretty new to this, so any suggestions on best practice would be appreciated. Thanks for helping out.

Server.js


app.get(`/getmovies`, (req, res) => {

    request(`/?t=${data}&apikey=${API_KEY}`,
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var parsedBody = JSON.parse(body);
                res.send(parsedBody)

            } else {
                console.log("error in the server")
            }
        }
    )
})


app.post('/postmovie', (request, response) => {
    console.log("I got a request!")
    console.log(request.body);
    const data = request.body;
    response.json({
        status: 'success',
        name: data
    })
})


///Client 

  postMovie = async (e) => {
    e.preventDefault();

    const data = this.state.movie;
    const options = {
      method: 'Post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    };

    const response = await fetch('/postmovie', options);
    const json = await response.json();
    console.log(json);


  };



  getMovies = (e) => {
    e.preventDefault();
    const { movie } = this.state;
    axios.get(`/getmovies`)
      .then(response => this.setState({ movies: response.data }))
      // .then(response => this.setState({ movies: response.data }))
      .catch(err => console.error(err))
  }

  render() {
    const { movie } = this.state;
    return (
      <div>
        <section className="form-container">
          <div className="movie-form-div">


            < form>
              <input className="form-input" type="text" name="name"
                value={movie.name}
                onChange={e => this.setState({ movie: { ...movie, name: e.target.value } })} />
              <button onClick={this.getMovies}>Search</button>
              <button onClick={this.postMovie}>Post</button>

            </form >
          </div>
        </section>



I am receiving my data from my POST request. I want to use that data as a variable in a GET request.The data from the POST request is user inputted to make different queries on the 3rd party API> How can I save my data as a variable to do so? You can see my request.body is being saved as const data. And I need it used as ${data} in my get request. I am pretty new to this, so any suggestions on best practice would be appreciated. Thanks for helping out.

Server.js


app.get(`/getmovies`, (req, res) => {

    request(`http://www.omdbapi./?t=${data}&apikey=${API_KEY}`,
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var parsedBody = JSON.parse(body);
                res.send(parsedBody)

            } else {
                console.log("error in the server")
            }
        }
    )
})


app.post('/postmovie', (request, response) => {
    console.log("I got a request!")
    console.log(request.body);
    const data = request.body;
    response.json({
        status: 'success',
        name: data
    })
})


///Client 

  postMovie = async (e) => {
    e.preventDefault();

    const data = this.state.movie;
    const options = {
      method: 'Post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    };

    const response = await fetch('/postmovie', options);
    const json = await response.json();
    console.log(json);


  };



  getMovies = (e) => {
    e.preventDefault();
    const { movie } = this.state;
    axios.get(`/getmovies`)
      .then(response => this.setState({ movies: response.data }))
      // .then(response => this.setState({ movies: response.data }))
      .catch(err => console.error(err))
  }

  render() {
    const { movie } = this.state;
    return (
      <div>
        <section className="form-container">
          <div className="movie-form-div">


            < form>
              <input className="form-input" type="text" name="name"
                value={movie.name}
                onChange={e => this.setState({ movie: { ...movie, name: e.target.value } })} />
              <button onClick={this.getMovies}>Search</button>
              <button onClick={this.postMovie}>Post</button>

            </form >
          </div>
        </section>



Share Improve this question edited Feb 3, 2020 at 19:09 saladWithRanch asked Feb 3, 2020 at 18:40 saladWithRanchsaladWithRanch 1682 gold badges2 silver badges9 bronze badges 6
  • Have you tried setting a global variable? Otherwise you can't and it makes no sense. They are differently scoped. Furthermore, if node.js is anything like the other web languages, end points will be possibly on different threads (not sure about node). Anyway, you shouldn't do this because you will also lose your data every time the app restarts. Use a database to save information like everyone else – sinanspd Commented Feb 3, 2020 at 18:47
  • Just to be clear, setting a global variable also doesn't make sense. Terrible practice. – sinanspd Commented Feb 3, 2020 at 18:53
  • It wouldn't make sense to store it into a database, when it is only going to be used one time. It is just a query parameter for a 3rd party api, to display a movie. It could easily be done client side, but an API key is involved. – saladWithRanch Commented Feb 3, 2020 at 18:58
  • why not pass the API key with the application config? I am not seeing why it has to e from the client side? Are they one use keys? Regardless, worst case why not make it a query parameter for the get request? Or set a cookie – sinanspd Commented Feb 3, 2020 at 19:01
  • I don't know how to do any of those things, which is why I am asking the question. Haha. It has to e from the client side because it is a variable that the user inputs. – saladWithRanch Commented Feb 3, 2020 at 19:05
 |  Show 1 more ment

1 Answer 1

Reset to default 3

As I have mentioned in the ments, your question is worded such that you make it sound like you absolutely need two requests.

Per the ments, OP has clarified that they don't necessarily need two requests so on that note here are a few things that you can try.

1) Set up an application.conf

Configuration files allow us to parameterize and configure variables that our applications need to function. You can vary the config files between environments (dev/stage/prod etc.) and deployments.

This will assume your API_KEY doesn't change frequently. Think of it as hard coding your api key like

var apiKey = "...."

but a better and more secure way of doing so.

In your case this won't work but it is good to be aware of it. You can use this package in the future

2) Get request query parameters.

This is your best bet

Query parameters, as the name suggest, allow us to pass in variables with the get requests to filter the results in the server side. This can be something like a user-id, page number etc.

Your get url from the client side would look like something like this

mydomain./getmovies?apikey={YourKeyGoesHere}

I am sure you have seen that ? in many of the urls you visit.

If you are using express your end point will look something like this.

app.get(`/getmovies`, (req, res) => {
   var apiKey = req.query.apikey
   request(`http://www.omdbapi./?t=${data}&apikey=${apikey}`,
      function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var parsedBody = JSON.parse(body);
            res.send(parsedBody)

        } else {
            console.log("error in the server")
        }
    }
)
})

See How to get GET (query string) variables in Express.js on Node.js?

This will allow you to pass it from the client side.

If you are not using express please see https://nodejs/api/querystring.html

3) If you absolutely need two endpoints...

Use a cookie. Once a cookie is set, it is transported back and forth with every request, until it expires.

See this How to set cookie in node js using express framework? or this

Once you receive the post request you would set a cookie

app.post('/postmovie', (request, response) => {
    response.cookie("apikey", data, maxAge: 900000, httpOnly: true });
    response.json({
      status: 'success'
    })
})

Once this cookie is set, it will be transported to the client and back with all the requests including the get.

So in your get request you can do:

app.get(`/getmovies`, (req, res) => {
   var apikey = req.cookies.apikey;
   request(`http://www.omdbapi./?t=${data}&apikey=${apikey}`,
      function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var parsedBody = JSON.parse(body);
            res.send(parsedBody)

        } else {
            console.log("error in the server")
        }
    }
)
})

So what's the difference between #2 and #3?

The query parameters that are encoded in the url are public and can be intercepted. This is fine for things like page numbers but if the API key is a paid one, this isn't very safe. Also once you submit the query, it is gone (unless you save the api key in the client side to the memory or local storage) so the user will have to potentially re-enter the api key everything.

Cookies on the other hand are private. The http-only flag we set in the code, prevents even the browser from reading it. Only the issuing server can see the contents. Plus cookies get stored in the browser until the expiration date so they can be reused with multiple requests.

Pick the one that works for you.

P.S. I didn't test the code above, you may need to tweak it a little bit. The answer is to give you a general idea on how these things are usually handled

本文标签: