POST Request with Fetch API?

后端 未结 5 1728
鱼传尺愫
鱼传尺愫 2020-12-01 03:10

I know that with the new Fetch API (used here with ES2017\'s async/await) you can make a GET request like this:

async getData() {
          


        
5条回答
  •  旧时难觅i
    2020-12-01 03:37

    Here is a solution for a POST request using node-fetch, with async/await.

    async function post(data) {
        try {
            // Create request to api service
            const req = await fetch('http://127.0.0.1/api', {
                method: 'POST',
                headers: { 'Content-Type':'application/json' },
                
                // format the data
                body: JSON.stringify({
                    id: data.id,
                    foo: data.foo,
                    bar: data.bar
                }),
            });
            
            const res = await req.json();
    
            // Log success message
            console.log(res);                
        } catch(err) {
            console.error(`ERROR: ${err}`);
        }
    }
    
    // Call your function
    post() // with your parameter of Course
    

提交回复
热议问题