Axios post request parameters to backend are undefined

 ̄綄美尐妖づ 提交于 2020-08-26 07:46:49

问题


I'm creating a simple ReactJs and I created a Searchbar component that does a post request when the user types something into the searchbar. This is the function that does the call:

const searchApi = searchTerm => 
axios.post('http://localhost:3000/findMovie', {
headers: {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
},
params: searchTerm
});

and it is being called in the onChange function like this:

handleInput = async (ev) => {
const value = ev.target.value;
const resultsBody = await searchApi(ev.target.value);

and this is what I do in my server.js file:

app.post('/findMovie', (req, res) => {
console.log('request:', req.params);

// axios.get('http://www.omdbapi.com/?apikey='+ 
// process.env.OMDB_API_KEY + '&s=' +)
})

I expected the console.log in the backend to show me the request parameters so that I can later do my api call to the external api and return the results, but the console.log show an empty object.

I'm quite new to this but shouldn't I do a post request for something like this? I also tried the same with a get request but it also didn't work.


回答1:


Your problem is caused by naming confusion between axios and express. params property in axios is sent as search parameters in the url.

In express url search parameters are available through query property, not params. So, try this:

app.post('/findMovie', (req, res) => {
  console.log('request:', req.query);
})

params property on an express request object refers to named route parameters, as in /users/:userId/edit.

More on that in express docs: https://expressjs.com/en/guide/routing.html#route-parameters

Update

Also, in order for the axios.post method to work properly, you need to change your call a little bit. It expects the post data a second argument. Since you're not sending any data in the body, you can provide an empty object:

const searchApi = searchTerm => 

    axios.post('http://localhost:3000/findMovie', {} /* <-- this guy */, {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    params: searchTerm
  });

Without it, your config object is wrongfully treated as post data.




回答2:


Try your axios function like this, set the params property as an object:

const searchApi = searchTerm => 
    axios.post('http://localhost:3000/findMovie', {
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    },
    params: { searchTerm }
});

And on the server you need to use req.query:

app.post('/findMovie', (req, res) => {
    console.log('request:', req.query);
})

You should be able to get the param as req.query.searchTerm



来源:https://stackoverflow.com/questions/53739951/axios-post-request-parameters-to-backend-are-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!