简体   繁体   English

Fetch Post在redux-saga中不起作用?

[英]Fetch Post not working in redux-saga?

I have the following code by using redux-saga to send a post request: 我有以下代码使用redux-saga发送帖子请求:

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? 但是使用'OPTION'方法发送ajax,我的代码出了什么问题? 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 . 您发送请求的服务器必须配置为发送其值包含Content-TypeAccess-Control-Allow-Headers响应头。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains what's happening here. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests解释了这里发生了什么。 Your request triggers your browser to send a CORS “preflight”. 您的请求会触发您的浏览器发送CORS“预检”。

The specific reason the browser does the preflight in this case is that the request includes a Content-Type: application/json request header. 在这种情况下,浏览器执行预检的具体原因是请求包括Content-Type: application/json请求标头。 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 . CORS协议要求如果跨源请求包含Content-Type请求标头,其值不是application/x-www-form-urlencodedmultipart/form-datatext/plain ,则浏览器发送OPTIONS请求并且然后检查对该响应的响应,以查看响应是否包含其值包含Content-TypeAccess-Control-Allow-Headers响应头。

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. 如果浏览器发现响应包含包含该值的响应头,则浏览器将继续发送您尝试使用代码生成的实际POST请求。 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 . 但是,如果浏览器发现响应不包含该标头,或者标头不包含Content-Type ,则浏览器将停在那里而不发送POST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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