【问题标题】:Spring MVC with Reactjs fetch error带有 Reactjs 的 Spring MVC 获取错误
【发布时间】:2018-10-12 22:27:48
【问题描述】:

我从(这里)[Getting "TypeError: failed to fetch" when the request hasn't actually failed

收到了类似的错误

我的方法用@CrossOrigin注解

使用邮递员我的请求可以正常工作(来自本地)

请参阅带有标头 Content-Type application/x-www-form-urlencoded 的 POST 到 http://star-is.info:8080/app-1.0.0-BUILD-SNAPSHOT/register 并传递带有名字的字符串

本地工作正常,但我的表单(此处)[http://star-is.info:8082/] 没有

       const data = {};
        data['firstname'] = this.state.firstname;
        console.log('submitSignup');
        fetch('http://localhost:8080/app-1.0.0-BUILD-SNAPSHOT/register', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then((response) => response.json()
        .catch(err => {
            console.err(`'${err}' happened!`);
            return {};
        })).then(function (body) {
            console.log(body);
        })
        .catch(error => {
     alert(error);
  });

现在我收到了来自服务器的回复

{名字:空}

但是为什么名字没有被传递到服务器..

我实现这一点的方法是使用寄存器作为端点来调用 fetch 并在 package.json 中使用代理


我用数据删除了 JSON.stringify,但它仍然为空

与邮递员一起看,我得到了相同的字符串


我什至试过这个

const data = {'firstname' : this.state.firstname};

它仍然返回 null

【问题讨论】:

  • @S.Iqbal 也请分享错误。
  • 类型错误未能获取.....我帖子的第 1 行

标签: javascript reactjs spring-mvc


【解决方案1】:

终于成功了。我必须对发送的数据进行编码。对于更复杂的对象,是否有更好的方法在 Reactjs 中执行此操作

const searchParams = Object.keys(data).map((key) => { return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]); }).join('&');

然后在fetch的body中使用searchParams

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多