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

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

问题描述

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

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 更具体:unexpected token W in json at position 0" -- 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天全站免登陆