我不断收到错误消息“字符串与预期模式不匹配"​​.为我的提取请求 [英] I keep getting the error "the string did not match the expected pattern" for my fetch request

查看:69
本文介绍了我不断收到错误消息“字符串与预期模式不匹配"​​.为我的提取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的提取请求,我不断收到错误消息字符串与预期模式不匹配"​​.我在这里和其他论坛上已经看到一些人有类似的问题,但是无法查明问题所在.如果有人有任何建议,请告诉我.

I keep getting the error "the string did not match the expected pattern" for my fetch requests. I've seen some people having similar problems on here and other forums but can't pinpoint the problem. If anyone has any suggestions, please let me know.

function showRecipes(){
            const ingredients = document.getElementById('ingredients').value.replace(/\s/g, "");
            const meal = document.getElementById('meal').value;
            const display = document.getElementById('display'); //Where results will go

            let url = 'http://www.recipepuppy.com/api/';
            url += `?i=${ingredients}&q=${meal}`;

            fetch(url, { mode: "no-cors"})
                .then(response => {
                    response.json()
                        .then(data => {
                            data.results.forEach(recipe => {
                                const container = document.createElement('div');
                                container.setAttribute('class', 'container');

                                const h1 = document.createElement('h1');
                                h1.textContent = recipe.title;

                                const p = document.createElement('p');
                                p.textContent = recipe.ingredients;

                                display.appendChild(container);
                                container.appendChild(h1);
                                container.appendChild(p);
                            })
                        })
                        .catch(err => {
                            console.log(err);
                        })
                })
                .catch(err => {
                    console.log('ERROR: ' + err);
                })
        }

推荐答案

如果服务器的响应为文本,但尝试使用 res.json()将其解析为JSON,则可能会收到此错误.

You may get this error if the server's response is text but you attempt to parse it as JSON using res.json().

fetch(serverUrl, {method: 'GET'})
.then((res) => res.json())

如果服务器返回文本,则

res.text()是合适的.

res.text() is appropriate if the server returns text.

在这种情况下,Safari曾经给我OP的错误,但是Chrome更具体:"json位置0处的json中意外的令牌W" - res.json()期望字符串的第一个字符为 { [",因为这是JSON的开始方式.

In this situation Safari once gave me the OP's error, but Chrome was more specific: "unexpected token W in json at position 0" -- res.json() expects the first character of the string to be { or [ since that is how JSON begins.

或者,就像Safari会说的那样,字符串与预期的模式不匹配."

Or, as Safari would say, "the string did not match the expected pattern."

这篇关于我不断收到错误消息“字符串与预期模式不匹配"​​.为我的提取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆