Home / MAD2 / Week 5 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
The developer wants to view the app in the browser locally for development. They run the following command: bash:
Which of the following best describes what happens and what the developer should have run instead?```json
{
"name": "my-vue-app",
"version": "0.1.0",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"vue": "^2.6.14"
},
"devDependencies": {
"@vue/cli-service": "^5.0.0",
"babel-eslint": "^10.1.0"
}
}
```
```
npm run build
```
launches the app on
; the developer should have run npm start to compile for production instead.``` npm run build ``` ``` localhost:8080 ```
and
do the same thing — both launch the app at 
``` npm run build ``` ``` npm run serve ``` ``` localhost:8080 ```
is correct for local development;
is only used for deploying to a server.``` npm run build ``` ``` npm run serve ```
compiles and bundles the app for production into a
folder — it does not start a local server. The developer should have run
instead.``` npm run build ``` /dist ``` npm run serve ```

```javascript
const user = {
id: 1,
profile: {
name: "Riya",
address: {
city: "Pune",
zip: "411001"
}
}
};
const {
profile: {
name,
address: { city, state = "Maharashtra" }
},
role = "guest",
profile
} = user;
console.log(name, city, state, role);
console.log(profile);
```

Riya Pune Maharashtra guest
```
{ name: "Riya", address: { city: "Pune", zip: "411001" } }
```

Riya Pune Maharashtra guest undefined

```
undefined undefined Maharashtra guest
```
```json
{ "name": "Riya", "address": { ...} }
```
, because you cannot destructure profile into nested variables and also assign it to a plain variable profile in the same statement.SyntaxError
What is the order of console output?```javascript
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
Promise.resolve().then(() => {
console.log("5");
setTimeout(() => console.log("6"), 0);
});
```
Based on the above data, answer the given subquestions.
pauses the execution of the
function until the Promise resolves.await ``` display() ```
immediately returns the resolved string "Data Received".``` fetchData() ```
functions cannot return a
.async Promise
would cause
to store a
object instead of the resolved value.await result Promise
Assume the API returns:
Complete the missing code so that all course names are rendered correctly. Which of the following code snippets can correctly replace
?```html
<div id="app">
<ul>
<!-- Missing Code -->
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
courses: []
},
async mounted() {
const response = await fetch('https://example.com/api/courses')
this.courses = await response.json()
}
})
</script>
```
```json
[
{ "id": 1, "name": "MAD-2" },
{ "id": 2, "name": "DBMS" }
]
```
```html
<!-- Missing Code -->
```
```html
<li v-for="course in courses" :key="course.id">
{{ course.name }}
</li>
```
```html
<li v-for="(course, index) in courses" :key="index">
{{ course.name }}
</li>
```
```html
<li v-if="course in courses">
{{ course.name }}
</li>
```
```html
<li v-for="courses in course">
{{ courses.name }}
</li>
```
```javascript
const products = [
{ name: "Laptop", price: 1200, inStock: true },
{ name: "Mouse", price: 25, inStock: false },
{ name: "Keyboard", price: 75, inStock: true },
{ name: "Monitor", price: 300, inStock: false }
];
const result = products.filter(item => item.inStock && item.price < 500);
```
```json
{ "name": "Keyboard", "price": 75, "inStock": true }
```
```
[[{ name: "Laptop", price: 1200, inStock: true }, { name: "Keyboard", price: 75, inStock: true }]]
```
```
[[{ name: "Keyboard", price: 75, inStock: true }]]
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
border: 1px solid black;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: flex-start;
align-content: flex-start;
height: 300px;
border: 2px solid red;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
<div class="box">Box 5</div>
<div class="box">Box 6</div>
</div>
</body>
</html>
```
The above code is initially loaded on the browser and then the browser is refreshed two times. What will be the final output?```javascript
function addProduct(product) {
let products = JSON.parse(localStorage.getItem('products')) || [];
products.push(product);
localStorage.setItem('products', JSON.stringify(products));
}
function getProducts() {
return JSON.parse(localStorage.getItem('products')) || [];
}
addProduct({ id: 3, name: 'Tablet' }.name);
console.log(getProducts());
```
```javascript
async function getUser() {
const response = await fetch("https://api.example.com/user/1");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
console.log(data.name);
}
getUser();
```
should use POST method by default, not GET``` fetch() ```
and
will throw errors because response is a 
response.ok ``` response.json() ``` Promise
cannot be called on a
response; use
instead``` .json() ``` fetch ``` .text() ```
does not work inside
functions``` fetch() ``` async

```javascript
console.log("A")
setTimeout(() => console.log("B"), 0)
Promise.resolve().then(() => console.log("C"))
console.log("D")
```
What will be the output of above code on the browser’s console?```javascript
async function fetchData() {
console.log("1");
const result = await new Promise((resolve) => {
setTimeout(() => resolve("done"), 1000);
console.log("2");
});
console.log("3:", result);
}
fetchData();
console.log("4");
```
```
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
setTimeout(() => {
state.cart.push(product)
}, 500)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
fetch('/api/add').then(() => {
state.cart.push(product)
})
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
Promise.resolve().then(() => {
state.cart.push(product)
})
}
}
```
file2: ProfileComponent.vue


```
{ path: "Settings" }
```
```json
{ path: "SettingsComponent" }
```
```json
{ "name": "Settings" }
```
```json
{ "name": "SettingsComponent" }
```
.In authentication using Flask-JWT-Extended, what does the payload part of the JWT stores?``` "header.payload.signature" ```
What will be the output of the above program?```javascript
const promise = new Promise((resolve, reject) => {
resolve('Success!');
reject('Error!');
});
promise.then(console.log).catch(console.log);
```
What will be printed in the console when the above code is executed?```javascript
const CAPACITY = 75;
const TOTAL_PEOPLE = 213;
function allocatePeople() {
return new Promise((resolve, reject) => {
let slots = [0, 0, 0];
let remaining = TOTAL_PEOPLE;
for (let i = 0; i < slots.length; i++) {
if (remaining >= CAPACITY) {
slots[i] = CAPACITY;
remaining -= CAPACITY;
} else {
slots[i] = remaining;
remaining = 0;
}
}
reject(slots);
});
}
async function startAllocation() {
try {
const result = await allocatePeople();
console.log("Passed " + JSON.stringify(result));
} catch (error) {
console.log("Failed " + JSON.stringify(error));
}
}
startAllocation();
```
Three requests are made to this application: GET /api/open (no authentication headers)1. GET /api/secure (no authentication headers)2. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser')3. What will be the response status codes for these requests, respectively?```python
@app.route('/api/open')
def open_endpoint():
return jsonify({'message': 'Open access', 'status': 'success'})
@app.route('/api/secure')
@auth_required('token')
def secure_endpoint():
return jsonify({'message': 'Secure access', 'status': 'authenticated'})
@app.route('/api/superuser')
@auth_required('token')
@roles_required('superuser')
def superuser_endpoint():
return jsonify({'message': 'Superuser access', 'status': 'authorized'})
```
If a user visit index.html at 10:10:10 AM, what will be logged in the console?

app.py:
```python
from flask import Flask, jsonify
from datetime import datetime
import time
app = Flask(__name__)
@app.route('/')
def home():
time.sleep(10)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
@app.route('/profile')
def profile():
time.sleep(30)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(debug=True)
```
index.html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script>
function test() {
const res1 = fetch('http://127.0.0.1:5000')
const res2 = fetch('http://127.0.0.1:5000/profile')
res1
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
res2
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
}
test()
</script>
</body>
</html>
```
You are developing an analytics platform using Flask and Flask-JWT-Extended. A user sends a POST request to
with:
. Then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required, get_jwt_identity
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username")
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route("/stats")
@jwt_required()
def stats():
current_user = get_jwt_identity()
return jsonify(message=f"Welcome {current_user}")
```
/login
```json
{ "username": "Jassi" }
```
/stats
route will return "Welcome Jassi" only if a valid JWT token is sent in the Authorization header/stats
will result in an unauthorized error/stats

/stats
Which of the following statements correctly explain why the Assignments page takes time to load?```javascript
export default {
data() {
return {
assignments: []
}
},
created() {
fetch("/api/assignments")
.then(res => res.json())
.then(data => {
this.assignments = data;
});
}
}
```
Backend: app.py

```javascript
methods: {
async login() {
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: this.email, password: this.password })
});
const data = await response.json();
console.log(data.message);
}
}
```
```python
@app.route('/login', methods=['POST'])
def login():
email = request.json['email']
password = request.json['password']
query = f"SELECT * FROM users WHERE email = '{email}'" \
f" AND password = '{password}'"
result = db.execute(query)
if result:
return jsonify({"message": "Login successful"})
return jsonify({"message": "Invalid credentials"})
```
What will be printed on the console first?```javascript
const store = new Vuex.Store({
state: { todos: [] },
mutations: {
addTodo(state, todo) { state.todos.push(todo) }
},
actions: {
async addTodoAsync({ commit }, todo) {
commit('addTodo', { text: todo, done: false });
return 'done';
}
}
});
store.dispatch('addTodoAsync', 'Learn Vuex')
.then(msg => console.log(msg));
console.log(store.state.todos.length);
```
What will be printed to the console?```javascript
function task(value) {
return new Promise((resolve, reject) => {
if (value > 5) {
resolve(value + 2);
} else {
reject(value - 2);
}
});
}
async function execute() {
try {
const a = await task(7);
const b = await task(a - 4);
return a + b;
} catch (err) {
return err;
}
}
execute().then(result => console.log(result));
```
Which of the following options correctly matches Concept / Issue and Description?| Concept / Issue | Description | |---|---| | A. "Chatty" nature of REST APIs | 1. Static HTML is enhanced with event handlers after initial page load | | B. Limitation of REST as a query mechanism | 2. May require multiple API calls to fetch data for a single view | | C. JavaScript Hydration | 3. Focuses on decoupling storage, logic, and presentation using APIs | | D. JAMStack approach | 4. Does not allow clients to specify exactly what data is required in one request |
Which of the following statements is/are CORRECT about this implementation?```javascript
mounted() {
const storedToken = localStorage.getItem('userToken');
if (storedToken) {
this.validateToken(storedToken)
.then(user => {
this.user = user;
this.isAuthenticated = true;
})
.catch(err => {
localStorage.removeItem('userToken');
this.isAuthenticated = false;
});
}
}
```
The above code is initially loaded in the browser, and then the browser is refreshed two times. What will be the final output printed in the console?```javascript
function addItemToCart(item) {
let cart = JSON.parse(localStorage.getItem('cart')) || [];
cart.push(item);
localStorage.setItem('cart', JSON.stringify(cart));
}
function getCartItems() {
return localStorage.getItem('cart') || [];
}
addItemToCart({ id: 1, name: 'Laptop' }.name);
console.log(getCartItems());
```
``` [] ```

``` ['Laptop', 'Laptop', 'Laptop'] ```

```
[{ id: 1, name: 'Laptop' }]
```
[undefined]
Which of the following is the correct matching?| Storage Type | Characteristic | | :---------------- | :-------------------------------------------------------------------------------- | | 1. Session Storage | A. Data automatically encrypts itself without developer intervention. | | 2. Token Storage | B. Data persists only until the browser/tab is closed. | | 3. Cookie Storage | C. Often used to store authentication tokens securely on the client side. | | | D. Data persists across sessions, typically stored on the client and sent with every HTTP request. |
What will be printed on the console?```javascript
Promise.resolve(1)
.then(v => { throw v + 1 })
.catch(e => e * 2)
.then(console.log)
```
```python
response.set_cookie('session_id', 'abc123', secure=option1,
samesite=option2)
```
Promise rejects automatically

Promise resolves and `response.ok = true`

Promise resolves and `response.ok = false`

Promise stays as pending
What will be the output?```javascript
const p = Promise.resolve(1)
.then(v => { console.log("A", v); return v + 1; })
.then(v => { console.log("B", v); throw "err"; })
.catch(e => { console.log("C", e); return 10; })
.then(v => console.log("D", v)));
console.log("END");
```
``` END A 1 B 2 C err D 10 ```

``` A 1 B 2 END C err D 10 ```

``` END A 1 C err D 10 ```

``` END A 1 B 2 C err ```

```javascript
const processString = (str) => {
return new Promise((resolve) => {
setTimeout(() => resolve(str.toUpperCase()), 100);
});
};
Promise.resolve('hello')
.then(processString)
.then(result => result + ' WORLD')
.then(console.log)
.catch(err => console.log('Error:', err));
```
Consider the following JavaScript code snippet.
```javascript
const users = [
{ name: "Amit", age: 25 },
{ name: "Bhavna", age: 20 },
{ name: "Chirag", age: 30 },
];
const names = users
.filter((u) => u.age >= 25)
.map((u) => u.name.toUpperCase())
.sort();
console.log(JSON.stringify(names));
```
What is logged on the console?
What will be the order of console output when the following JavaScript code is executed?
```javascript
async function test() {
console.log("P");
await Promise.resolve();
console.log("Q");
}
console.log("R");
test();
console.log("S");
```
Consider the following javascript program.
What will be the output of the above program on the browser’s console?```javascript
new Promise((resolve, reject) => {
const score = 0.45;
if (score >= 0.5) {
resolve(score);
} else {
reject(new Error("Score too low"));
}
})
.then(data => {
console.log("Stage A:", data);
return data * 10;
})
.catch(error => {
console.log("Stage B:", error.message);
return 3;
})
.then(data => {
console.log("Stage C:", data);
if (data < 5) {
throw new Error("Value below threshold");
}
return data + 2;
})
.then(data => {
console.log("Stage D:", data);
return data / 2;
})
.catch(error => {
console.log("Stage E:", error.message);
if (error.message === "Value below threshold") {
return "Recovered";
}
throw error;
})
.then(data => {
console.log("Stage F:", data);
if (data === "Recovered") {
return 10;
}
return data * 4;
})
.finally(() => {
console.log("Stage G: Cleanup completed");
});
```
```text Stage A: 0.45 Stage C: 4.5 Stage D: 6.5 Stage F: 26 Stage G: Cleanup completed ```

```text Stage B: Score too low Stage C: 3 Stage E: Value below threshold Stage F: Recovered Stage G: Cleanup completed ```

Stage A: 0.45 Stage C: 4.5 Stage E: Value below threshold Stage F: Recovered Stage G: Cleanup completed

``` Stage B: Score too low Stage C: 3 Stage D: 5 Stage F: 20 Stage G: Cleanup completed ```

Given the Flask app:
```python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
@app.route('/api/data')
def data():
return {"msg": "Success"}
```
frontend code:
```javascript
fetch("http://localhost:5000/api/data")
.then(res => res.json())
.then(data => console.log(data));
```
What will happen when run from a Vue app hosted at http://localhost:5173?
Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single-player game that finishes when the game loop ends.
To compare productivity:
● If Prashant and Nikita (together) finish faster than Mayur, the winner is "Team". ● If Mayur finishes faster, he wins. ● If both take the same time, Mayur wins by default.
You are simulating this scenario in the browser.Prashant and Nikita are represented using parallel Promises. Mayur is represented using a single Promise. The frontend must calculate who finishes first using asynchronous logic, and display the result.
Based on the above data, answer the given subquestions. 
app2.js
```javascript
async function playGame() {
const start = Date.now();
const prashantPromise = new Promise(resolve =>
setTimeout(resolve, 3000));
const nikitaPromise = new Promise(resolve =>
setTimeout(resolve, 2000));
const mayurPromise = new Promise(resolve =>
setTimeout(resolve, 2000));
await Promise.all([prashantPromise, nikitaPromise]);
const teamTime = Date.now() - start;
await mayurPromise;
const mayurTime = Date.now() - start;
const winner = (teamTime < mayurTime) ? "Team" : "Mayur";
console.log(`Winner is: ${winner}`);
}
```
Suppose a client wants to make a **POST** request using the Fetch API to a public endpoint at **/api/submit**, which includes sending a **data** object as JSON in the request body.
```javascript
const data = {
name: "Aditya",
score: 95,
};
fetch("/api/submit", {
method: "POST",
headers: {
// CODE
},
body: JSON.stringify(data),
});
```
Which headers are necessary for this request to succeed, (inside CODE)?
``` 'Content-Type': 'application/json' ```

``` 'Content-Type': 'multipart/form-data' ```

``` 'Content-Type': 'application/text' ```

``` 'Accept': '*/*' ```

Consider the following code snippet.
```javascript
const response = {
meta: () =>
Promise.resolve([
{ id: 1, score: 20 },
{ id: 2, score: 40 },
]),
json: () =>
Promise.resolve([
{ name: "Alpha", score: 40 },
{ name: "Beta", score: 30 },
{ name: "Charlie", score: 50 },
{ name: "Delta" }, // no score
]),
};
fetchData();
function fetchData() {
Promise.resolve(response)
.then((res) => res.json())
.then((data) => {
const total = data
.map((p) => parseInt(p.score) || 0)
.filter((score) => score >= 40)
.reduce((acc, score) => acc + score, 0);
console.log("Total Score:", total);
});
}
```
What will be logged to the console?
Consider the following Vue 2 component defined using the CDN version:
Filename: index.html
```html
<div id="app">
<p>{{ message }}</p>
</div>
```
Filename: app.js
```javascript
new Vue({
el: '#app',
data() {
return {
message: 'Initial'
};
},
created() {
console.log('Created Hook');
this.message = 'Created Hook Called';
this.fetchData();
},
mounted() {
console.log('Mounted Hook');
},
methods: {
async fetchData() {
const res = await new Promise(resolve => {
setTimeout(() => resolve('Data Loaded'), 1000);
});
this.message = res;
console.log('Data updated after fetch');
}
}
});
```
What will be the sequence of console logs and final content shown on the web page after 1 second?
Console: Mounted Hook Created Hook Data updated after fetch Page: Initial

Console: ``` Created Hook Mounted Hook Data updated after fetch ``` Page: Data Loaded

Console: ``` Created Hook Data updated after fetch Mounted Hook ``` Page: Data Loaded

Console: Mounted Hook Data updated after fetch Created Hook Page: Created Hook Called

Consider the following JavaScript program:
```javascript
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('The cat sleeps');
}, 2000);
});
promise1
.then((result) => {
console.log(result);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Rain falls gently');
}, 1000);
});
})
.then((result) => {
console.log(result);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Books gather dust');
}, 1500);
});
})
.then((result) => {
console.log(result);
throw new Error('Coffee grows cold');
})
.then((result) => {
console.log('Stars shine bright');
})
.catch((error) => {
console.log("Caught:", error.message);
});
```
What will be the output of the above program when executed?
The cat sleeps Rain falls gently Books gather dust Stars shine bright

The cat sleeps Rain falls gently Books gather dust Caught: Coffee grows cold

The cat sleeps Rain falls gently Caught: Coffee grows cold

The program will crash without showing any output

The cat sleeps Rain falls gently Books gather dust Caught: Coffee grows cold Stars shine bright

Consider the below application with markup "index.html" and JavaScript file
"app.js".
Filename: index.html
```html
<div id="app"></div>
<script src="app.js"></script>
```
Filename: app.js
```javascript
const inventory = {
101: {product: "Canvas", quantity: 15, warehouse: 3},
102: {product: "Brushes", quantity: 8, warehouse: 2}
}
const errorPage = {
template: `<h1>Item not found in inventory!</h1>`
}
const productDetails = {
template: `<h1>{{item.product}} - {{item.quantity}} units stored
in
{{item.warehouse}} locations.</h1>`,
data() {
return {item: inventory[this.$route.params.productId]}
},
watch: {
'$route'(to, from) {
this.item = inventory[to.params.productId]
}
}
}
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/inventory/:productId', component: productDetails },
{ path: '*', component: errorPage },
],
})
new Vue({
el: '#app',
template: '<div><router-view /></router-view></div>',
router,
})
```
Suppose the application is running on "http://localhost:3000", select the correct option(s)?
For the endpoint, http://localhost:3000/inventory/101, The browser will render: Canvas - 15 units stored in 3 locations.

For the endpoint, http://localhost:3000/#/inventory/102, The browser will render: Brushes - 8 units stored in 2 locations.

For the endpoint, http://localhost:3000/inventory. The browser will render: item not found in inventory!

For the endpoint, http://localhost:3000/inventory/103, The browser will render: Item not found in inventory!

For the endpoint, http://localhost:3000/products/101, The browser will render: Item not found in inventory!

Consider the following Vuex store setup for a user management system:
```javascript
const store = new Vuex.Store({
state: {
users: [
{ id: 1, name: 'Alice', status: 'active', role: 'admin' },
{ id: 2, name: 'Bob', status: 'inactive', role: 'user' },
{ id: 3, name: 'Charlie', status: 'active', role: 'user' }
]
},
getters: {
activeUsers(state) {
return state.users.filter(user => user.status === 'active');
},
activeUserCount(state, getters) {
return getters.activeUsers.length;
},
adminUsers(state) {
return state.users.filter(user => user.role === 'admin');
}
},
mutations: {
updateUserStatus(state, { userId, status }) {
const user = state.users.find(u => u.id === userId);
if (user) {
user.status = status;
}
}
}
});
```
```javascript
addUser(state, user) {
state.users.push({ ...user, id: Date.now() });
},
actions: {
toggleUserStatus({ commit, state }, userId) {
const user = state.users.find(u => u.id === userId);
if (user) {
const newStatus = user.status === 'active' ? 'inactive' : 'active';
commit('updateUserStatus', { userId, status: newStatus });
}
},
async createUser({ commit }, userData) {
await new Promise(resolve => setTimeout(resolve, 100));
commit('addUser', userData);
}
}
```
What will happen when the following sequence of operations is executed?
```javascript
store.dispatch('toggleUserStatus', 1); // Toggle Alice's status
store.dispatch('createUser', { name: 'David', status: 'active', role: 'user' });
```
The activeUserCount will become 1 immediately after the first dispatch, and remain 1 after the second dispatch completes.

The activeUserCount will become 1 after the first dispatch, and become 2 after the second dispatch completes.

The activeUserCount will remain 2 after the first dispatch, and become 3 after the second dispatch completes.

The activeUserCount will become 3 immediately after both dispatches, since both operations run synchronously.
You are given the following HTML and JavaScript code that uses Vue 2 via CDN along with Vue Router. Read the code carefully and answer the given subquestions.
You are given the following HTML and JavaScript code that uses Vue 2 via CDN along with Vue Router. Read the code carefully and answer the given subquestions.

Add v-else after v-if instead of v-show.

Replace ```javascript await this.simulateApiCall().then(...); ``` with ```javascript const res = await this.simulateApiCall(); this.message = res; ```

Add a check to disable the button while loading; ```html <button @click="fetchData" :disabled="loading">Fetch</button> ```

Use v-html instead of v-show for message rendering.

```javascript
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
}
}
```
```javascript
computed: {
fullName: {
get() { return this.firstName + ' ' + this.lastName; },
set(value) {
const names = value.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
}
}
```
```javascript
computed: {
async fullName() {
return await this.fetchFullName();
}
}
```
```javascript
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
```
Consider the below JavaScript program.
```javascript
const promise = new Promise(((resolve, reject) => {
resolve('Success!');
reject('Failed!');
}));
promise.then(console.log).catch(console.log);
```
What will be the output of the above program?
Consider the following JavaScript code.
```javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('HTTP error');
const data = response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
return {
status: 'network error'
};
}
return {
status: 'http error'
};
}
}
```
When the function is called, what will be returned if the request gives a 200 OK?
```
{ status: 'http error' }
```
```
{ status: 'network error' }
```
JSON data

The promise will remain pending

Consider the below CORS enabled flask app.
```python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:5000"}})
@app.route("/api/data")
def data():
return {"message": "Hello from Flask"}
```
If a Vue.js frontend (simulation given below) at "http://localhost:3000" tries to fetch data, what will happen?
```javascript
fetch("http://localhost:5000/api/data")
.then(response => response.json())
.then(data => console.log(data));
```
Consider the below Vuex setup.
What is logged to the console immediately after dispatching the action?```javascript
const store = new Vuex.Store({
state: {
value: 0
},
mutations: {
setValue(state, payload) {
state.value = payload;
}
},
actions: {
async updateValue({
commit
}) {
const newValue = await fetchData();
commit('setValue', newValue);
}
}
});
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve(42), 2000);
});
}
store.dispatch('updateValue');
console.log(store.state.value);
```
Consider the following Flask application (server.py) and an HTML file named index.html:
server.py
```python
from flask import Flask
import time
app = Flask(__name__)
@app.route("/api/slow1")
def slow_api_1():
time.sleep(15)
return "Response from Slow API 1", 200, {'Access-Control-Allow-Origin': '*'}
@app.route("/api/slow2")
def slow_api_2():
time.sleep(25)
return "Response from Slow API 2", 200, {'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(threaded=False)
```
index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask Fetch Example</title>
</head>
<body>
<h1>Fetching API Data...</h1>
<script>
fetch("http://127.0.0.1:5000/api/slow1")
.then(res => res.json())
.then(data => console.log("API 1 Response:", data));
fetch("http://127.0.0.1:5000/api/slow2")
.then(res => res.json())
.then(data => console.log("API 2 Response:", data));
</script>
</body>
</html>
```
If you open index.html in a browser, approximately how long will it take for the second fetch call (http://127.0.0.1:5000/api/slow2) to complete and log the data to the console?
Consider the below flask implementation with JWT based authentication.
```python
from flask import Flask, request, jsonify
import jwt
import datetime
app = Flask(__name__)
SECRET_KEY = "supersecret"
def generate_token(user):
return jwt.encode(
{"user": user, "exp": datetime.datetime.utcnow() +
datetime.timedelta(seconds=10)},
SECRET_KEY,
algorithm="HS256"
)
@app.route("/login", methods=["POST"])
def login():
user = request.json.get("user")
token = generate_token(user)
return jsonify({"token": token})
@app.route("/protected", methods=["GET"])
def protected():
token = request.headers.get("Authorization").split(" ")[1]
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return jsonify({"message": f"Hello {payload['user']}!"})
except jwt.ExpiredSignatureError:
return jsonify({"error": "Token expired"}), 401
except jwt.InvalidTokenError:
return jsonify({"error": "Invalid token"}), 403
```
If a Vue.js client sends this request 15 seconds after login, what response will it receive
(assume the token sent is the one, which was received from login)?
```javascript
fetch("http://localhost:5000/protected", {
method: "GET",
headers: { "Authorization": "Bearer <JWT_TOKEN>" }
})
.then(res => res.json())
.then(console.log);
```
```json
{ "message": "Hello user!" }
```
```json
{ "error": "Token expired" }
```
```json
{
"error": "Invalid token"
}
```
```json
{
"message": "Access granted"
}
```

What will be the response
by the following fetch
request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET"
})
.then(response => {
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.


What will be the result of the following fetch request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET",
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.."
}
})
.then(response => {
if (response.status === 403) {
throw new Error("403 Forbidden: Insufficient permissions");
}
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.

Consider the below JavaScript program.
```javascript
const promise = new Promise(((resolve, reject) => {
reject('Error!');
resolve('Success!');
}));
promise.then(console.log).catch(console.log);
```
What will be the output of the above program?