标签: fetch

使用 PDO 返回数组 - 使用 FetchAll 不起作用

我使用以下代码从数据库中检索数据。问题是它只显示第一行。在这种特殊情况下,这意味着网页上仅显示第一张图片,但我想显示所有图片。

<?php 
    $sql = "SELECT `image-id`, `article-id`, `image-path`, `image-title` FROM `table-images` WHERE `article-id` = :id";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(":id", $id);
    $stmt->execute();

    if($result = $stmt->fetch(PDO::FETCH_ASSOC))
    {
?>

<a class="swipebox" href="<?php echo $result['image-path'];?>" title="<?php echo $result['image-title'];?>">
<img alt="image" src="<?php echo $result['image-path'];?>"></a>

<?php
    }// end if
    else {
    echo '0 results';
    }// end else
?>
Run Code Online (Sandbox Code Playgroud)

我读了这篇文章,所以我尝试使用代码:

if($result = $stmt->fetchAll(PDO::FETCH_ASSOC));?

...但这行不通。它甚至不再呼应第一张图片。我在这里缺少什么?

php sql pdo fetchall fetch

1
推荐指数
1
解决办法
6087
查看次数

对被 CORB 阻止的 html 资源获取的 no-cors 不透明请求

我正在尝试 从using模式中获取html位于 url 的文件,但响应被 CORB(跨源读取阻塞)阻止。https://sub.app.test/htmlhttps://app.testno-cors

fetch('https://sub.app.test/html', { mode: 'no-cors'})
Run Code Online (Sandbox Code Playgroud)

为什么?

fetch cors cross-origin-read-blocking

1
推荐指数
1
解决办法
750
查看次数

CORS Cookie 未在跨域上设置,使用 fetch,设置凭据:'include' 和 origins 已设置

我正在使用 fetch 向后端发出请求。当我使用不同的域时,cookie 未设置。当我使用相同的域时设置了 cookie。

为什么没有设置?

我修改了我的 /etc/hosts 文件以使用假名来测试使用相同和不同的域,并确保它们也没有被浏览器列入黑名单

如果我local-test-frontend.com同时用于浏览器和服务器域,它可以工作,但如果我将后端 url 更改为local-test-backend.com它会失败。

*请注意,我测试的前端网址是 * http://local-test-frontend.com:3000/login

Javascript

    fetch('http://local-test-backend.com/login',  {
        mode: 'cors',
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginRequest),
        credentials: 'include'
    }).then(// Other code here.....
Run Code Online (Sandbox Code Playgroud)

服务器响应头

Access-Control-Allow-Credentials    
true
Access-Control-Allow-Origin 
http://local-test-frontend.com:3000
Content-Length  
103
Content-Type    
application/json
Date    
Wed, 10 Jul 2019 07:23:49 GMT
Server  
Werkzeug/0.15.1 Python/3.7.3
Set-Cookie  
MY_TOKEN=a7b8ad50f19…end.com; Path=/; SameSite=Lax
Run Code Online (Sandbox Code Playgroud)

javascript cross-domain fetch cors flask

1
推荐指数
2
解决办法
3091
查看次数

React Native / Expo:Fetch 抛出“网络请求失败”

我看到了几个关于这个主题的帖子,但没有结果。一方面,我有一个收集信息(姓名、名字等)然后将其保存在数据库(mongodb)中的表单。当我使用邮递员通过路由/注册发送我的信息时,一切正常,我可以在 mongodb 中看到我的新用户。但是当我在 Expo 上启动应用程序时,他向我抛出“网络请求失败”。

前端获取:

submitForm = () => {
  var signupData = JSON.stringify({
    first_name: this.state.firstName,
    last_name: this.state.lastName,
    email: this.state.email,
    password: this.state.password
  });

  fetch(`https://localhost:3000/signup`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: signupData
  })
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(data => {
      if (data.result) {
        this.props.handleUserValid(
          this.state.firstName,
          this.state.lastName,
          this.state.email,
          data.user.token
        );
        this.props.navigation.navigate("Account");
      }
    })
    .catch(error => {
      console.error(error);
    });
};

Run Code Online (Sandbox Code Playgroud)

和后端路由:

router.post("/signup", function(req, res, next) {
  var salt = uid2(32);

  console.log("Signup is running...");
  const newUser = …
Run Code Online (Sandbox Code Playgroud)

api request fetch express react-native

1
推荐指数
3
解决办法
4962
查看次数

将 async-await 与 node-fetch 结合使用不会将响应返回给调用方法

我在模块中定义了一个函数,该函数应该执行获取并返回响应。我在从 fetch 返回响应时遇到问题。调用函数将返回值设为“未定义”。

我是 JavaScript 和 Node 的新手,所以如果你不介意的话,可能需要一点帮助。

调用函数

async function executeTest() {
    try {
        const response = await bpc.postLendingApplication(
            blendConnection,
            loanData
        );
        console.log("Response from POST Loan: ", response);
    } catch (error) {
        console.log(error);
    }
}
Run Code Online (Sandbox Code Playgroud)

执行获取请求的模块函数

const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
    console.log("Processing POST Loan.");
    await fetch(connection.url, {
        method: "POST",
        headers: connection.headers,
        body: data,
    }).then(async res => {
        console.log("Status: ", res.status);
        console.log("StatusText: ", res.statusText);
        console.log("OK: ", res.ok);
        return await res;
    });
}
Run Code Online (Sandbox Code Playgroud)

控制台输出是:

Processing POST Loan. …
Run Code Online (Sandbox Code Playgroud)

javascript fetch node.js async-await node-fetch

1
推荐指数
1
解决办法
7038
查看次数

当我有正确数量的字符时,为什么我的 Rails 应用程序返回“密码太短(最少 6 个字符)”?

我正在构建一个简单的注册页面。

这是我的用户模型及其验证和关联:

class User < ApplicationRecord
    has_secure_password

    has_many :posts
    has_many :comments
    has_many :likes

    validates :username, presence: true, uniqueness: true
    validates :password, presence: true, length: { minimum: 6 }
end
Run Code Online (Sandbox Code Playgroud)

这是我的用户迁移:

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :username
      t.string :password_digest
      t.integer :age
      t.integer :years_in_the_labor
      t.string :title
      t.string :location
      t.string :ministry

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这也是我的用户控制器创建方法:

def create
    @user = User.new(name: params[:name], title: params[:title], username: params[:username], password: [:password])

    if @user.valid?
        @user.save
        render json: { status: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails fetch bcrypt-ruby reactjs

1
推荐指数
1
解决办法
296
查看次数

将 SWR 与依赖的请求数据一起使用

我正在尝试使用 SWR 获取连接到自定义挂钩提供的登录用户 ID 的用户列表。

我不能把useSWR里面无论是useCallbackuseEffectif (loggedInAdvisor) { ... }...不能弄清楚如何做到这一点。

export const fetchDetailedAdvisorPrognoses = (
  body: DetailedAdvisorPrognosesRequest
): Promise<DetailedAdvisorPrognoses[]> | null => {
  const accessToken = getFromPersistance(ACCESS_TOKEN)

  if (!accessToken) {
    return null
  }

  return fetch('https://x/api/v2/advisors/prognoses', {
    method: 'POST',
    headers: {
      ...generateDefaultHeaders(),
      'Content-Type': 'application/json',
      Authorization: getAuthorizationHeader(accessToken),
    },
    body: JSON.stringify(body), // body data type must match "Content-Type" header
  }).then(res => res.json())
}

function Workload(): ReactElement | null {
  const { loggedInAdvisor } = useAuthentication() …
Run Code Online (Sandbox Code Playgroud)

fetch reactjs vercel

1
推荐指数
1
解决办法
4569
查看次数

从 Fetch 访问响应数据

这是我的提取功能:

getAllCountries = async () => {
    try {
      const response = await fetch("https://restcountries.eu/rest/v2/all");
      const result = response.json();
      console.log(result);
      this.countriesList = result;
    } catch (error) {
      console.log(error);
    }
  };
Run Code Online (Sandbox Code Playgroud)

在控制台中,它记录 在此处输入图片说明

为什么在那里登录了两个 Promise,以及如何访问 PromiseResult。我试过了,console.log(result[0])但没有用

javascript api fetch

1
推荐指数
1
解决办法
417
查看次数

“访问获取已被 CORS 政策阻止” Chrome 扩展程序错误

我知道这已经被问过很多次了,但在我看来,我已经做了所有正确的事情,但仍然无法让它发挥作用。

我正在尝试从 Chrome 扩展程序的后台脚本的外部 API 获取数据,使用消息传递从内容脚本启动调用并获取结果。我无法控制外部 API。该 API 的文档说使用脚本标签来获得 jsonp 响应,但如果我理解正确,那么在实现以下项目时应该无关紧要。我错了吗?

  • fetch() 在后台脚本中
  • “*://*/”在我的清单中的权限中(如果我可以让它工作,我会改变它,只是消除这种可能性)
  • 扩展是“打包”的

错误:从源“chrome-extension://bunchofchars”获取“https://external-api.com”的访问权限已被 CORS 政策阻止:对预检请求的响应未通过访问控制检查:无“访问” -Control-Allow-Origin' 标头存在于请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

关于我做错了什么的任何线索?

背景.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      fetch('https://api.com/' + request.user + 'restofurl',
          {
            method: 'get',
            headers: {'Content-Type':'application/json'}
          })
//          .then(response => parseResults(response.results))
          .then(response => sendResponse({result: response.results}))
//          .catch(error => ...)
      return true;
  });
Run Code Online (Sandbox Code Playgroud)

内容.js

(() => {
    function foo() {

        var parent = document.getElementById('someId');
        var username = parent.getElementsByTagName('a')[6].innerHTML;
        chrome.runtime.sendMessage({user: username}, function(response) {
            console.log(response.result);
        });
    window.addEventListener('load', foo);

})();
Run Code Online (Sandbox Code Playgroud)

javascript fetch google-chrome-extension cors

1
推荐指数
3
解决办法
3303
查看次数

为什么 fetch api 在 url %E2%80%8B 中添加转义字符

当我提供静态字符串来获取它时,我在反应服务中调用 fetch api 工作正常,如下所示

export const getAll = async (_url) => {
 const requestOptions = {
method: 'GET',
};

 try {
  const response = await fetch(
  process.env.REACT_APP_API_URL + '/api/communications/notifications/',  // like this
  requestOptions
);
    const json = await response.json();
return json;
} catch (error) {
return Promise.reject(error);
}
};
Run Code Online (Sandbox Code Playgroud)

url 形成 => http://localhost/api/communications/notifications/

但是当我将字符串从 action 传递给 service 并使用该参数(_url)时,它会像这样自动添加转义字符

url 形成 => http://localhost/api/communications%E2%80%8B/notifications%E2%80%8B/

这是我的操作文件代码

import { notificationConstants } from '../constants/header.constants';
import * as ajaxService from '../services/ajax.service';
import { toast } from …
Run Code Online (Sandbox Code Playgroud)

url fetch reactjs react-redux

1
推荐指数
1
解决办法
874
查看次数