简体   繁体   中英

Fetch Post not working in redux-saga?

I have the following code by using redux-saga to send a post request:

import {put, call, fork, takeEvery} from 'redux-saga/effects';
import fetch from 'isomorphic-fetch';
const url = 'xxx/api/posts';


function* addPost(data) {
    try{
        const response = yield fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify(data)
        });
        const id = yield response.json().id;
        yield put({type: types.ADD_POST, payload: {id, title, content }});
    }catch(e) {
        yield put({type: types.ERROR, payload: e});
    }
}

But an ajax is sent with the 'OPTION' method, what's wrong with my code? Why it doesn't work?

The server you're sending the request to must be configured to send an Access-Control-Allow-Headers response header whose value contains Content-Type .

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains what's happening here. Your request triggers your browser to send a CORS “preflight”.

The specific reason the browser does the preflight in this case is that the request includes a Content-Type: application/json request header. The CORS protocol requires that if a cross-origin request includes a Content-Type request header with a value other than application/x-www-form-urlencoded , multipart/form-data , text/plain , the browser sends an OPTIONS request and then checks the response to that to see if the response includes an Access-Control-Allow-Headers response header whose value contains Content-Type .

If the browser finds that the response includes a response header that includes that value, then the browser will then proceed to send that actual POST request you're trying to make with your code. But if the browser instead finds that the response doesn't include that header, or that the header doesn't contain Content-Type , then the browser will stop right there and not send the POST .

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